智慧食堂
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.

2489 lines
107 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")
  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. var userTotal, breakFastTotal, lunchTotal, dinnerTotal, supperTotal, totalTotal int64
  282. var breakFastAmountTotal, lunchAmountTotal, dinnerAmountTotal, supperAmountTotal, totalAmountTotal float64
  283. for kk, vv := range v {
  284. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{vv["编号"]["id"], kk,
  285. vv["早餐"]["num"], vv["早餐"]["amount"],
  286. vv["午餐"]["num"], vv["午餐"]["amount"],
  287. vv["晚餐"]["num"], vv["晚餐"]["amount"],
  288. vv["夜宵"]["num"], vv["夜宵"]["amount"],
  289. vv["合计"]["num"], vv["合计"]["amount"],
  290. })
  291. userTotal++
  292. if vv["早餐"]["num"] != nil {
  293. breakFastTotal += vv["早餐"]["num"].(int64)
  294. }
  295. if vv["午餐"]["num"] != nil {
  296. lunchTotal += vv["午餐"]["num"].(int64)
  297. }
  298. if vv["晚餐"]["num"] != nil {
  299. dinnerTotal += vv["晚餐"]["num"].(int64)
  300. }
  301. if vv["夜宵"]["num"] != nil {
  302. supperTotal += vv["夜宵"]["num"].(int64)
  303. }
  304. if vv["合计"]["num"] != nil {
  305. totalTotal += vv["合计"]["num"].(int64)
  306. }
  307. if vv["早餐"]["amount"] != nil {
  308. breakFastAmountTotal += vv["早餐"]["amount"].(float64)
  309. }
  310. if vv["午餐"]["amount"] != nil {
  311. lunchAmountTotal += vv["午餐"]["amount"].(float64)
  312. }
  313. if vv["晚餐"]["amount"] != nil {
  314. dinnerAmountTotal += vv["晚餐"]["amount"].(float64)
  315. }
  316. if vv["夜宵"]["amount"] != nil {
  317. supperAmountTotal += vv["夜宵"]["amount"].(float64)
  318. }
  319. if vv["合计"]["amount"] != nil {
  320. totalAmountTotal += vv["合计"]["amount"].(float64)
  321. }
  322. j++
  323. }
  324. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{"总计", userTotal,
  325. breakFastTotal, breakFastAmountTotal,
  326. lunchTotal, lunchAmountTotal,
  327. dinnerTotal, dinnerAmountTotal,
  328. supperTotal, supperAmountTotal,
  329. totalTotal, totalAmountTotal,
  330. })
  331. sheetIndex++
  332. }
  333. xlsx.DeleteSheet("template") //删除模板表
  334. //将文件保存至服务器
  335. xlsx.SaveAs("./static" + downloadPath)
  336. break
  337. case 2:
  338. //商家分餐数据统计表
  339. xlsx, _ := excelize.OpenFile("./static/template/自营学校(商家分餐数据统计表).xlsx")
  340. fileName = "商家分餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  341. downloadPath = "/export/self_support_for_school/" + fileName
  342. //查询出所有的设备
  343. var deviceList []*model.Device
  344. err := db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
  345. if err != nil {
  346. logx.Error(err)
  347. println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>1111Error:::", err.Error())
  348. return
  349. }
  350. var deviceListMapping = map[string]model.Device{}
  351. var deviceNameArr []string
  352. for _, v := range deviceList {
  353. deviceListMapping[v.DeviceSn] = *v
  354. deviceNameArr = append(deviceNameArr, v.Name)
  355. }
  356. var m []*db.SelfSupportForSchoolOrdWithUserIdentity
  357. sess := db.Db.Desc("self_support_for_school_ord.id")
  358. if req.EnterpriseId != 0 {
  359. sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
  360. }
  361. if req.StartDate != "" {
  362. sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
  363. }
  364. if req.EndDate != "" {
  365. sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
  366. }
  367. if req.EnterPriseKind != 0 {
  368. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  369. }
  370. _, err = sess.
  371. Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id").
  372. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  373. Join("LEFT", "user", "user.id = user_identity.uid").
  374. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  375. Join("LEFT", "class", "class_with_user.class_id = class.id").
  376. Join("LEFT", "grade", "class.grade_id = grade.id").
  377. FindAndCount(&m)
  378. if err != nil {
  379. logx.Error(err)
  380. println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
  381. return
  382. }
  383. //整合数据
  384. var data = map[string]map[string]map[string]map[string]float64{}
  385. for _, vv := range m {
  386. shopName := deviceListMapping[vv.SelfSupportForSchoolOrd.DeviceSn].Name
  387. if data[vv.Enterprise.Name] == nil {
  388. data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  389. }
  390. if data[vv.Enterprise.Name][shopName] == nil {
  391. data[vv.Enterprise.Name][shopName] = make(map[string]map[string]float64)
  392. }
  393. mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime)
  394. if data[vv.Enterprise.Name][shopName][mealZh] == nil {
  395. data[vv.Enterprise.Name][shopName][mealZh] = make(map[string]float64)
  396. }
  397. if data[vv.Enterprise.Name][shopName]["合计"] == nil {
  398. data[vv.Enterprise.Name][shopName]["合计"] = make(map[string]float64)
  399. }
  400. data[vv.Enterprise.Name][shopName][mealZh]["num"]++
  401. data[vv.Enterprise.Name][shopName][mealZh]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  402. data[vv.Enterprise.Name][shopName]["合计"]["num"]++
  403. data[vv.Enterprise.Name][shopName]["合计"]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  404. }
  405. xlsx.SetSheetRow("", "A1", &titleList)
  406. sheetIndex := 2 //第一个表是模板表
  407. for k, v := range data {
  408. if k == "" {
  409. k = "未知"
  410. }
  411. xlsx.NewSheet(k) //1、新建表格
  412. xlsx.CopySheet(1, sheetIndex)
  413. xlsx.SetSheetRow(k, "A1", &[]interface{}{"商 家 分 餐 数 据 统 计 表 " + "(" + req.StartDate + "至" + req.EndDate + ")"})
  414. j := 4 //表头前三行被占用了,只能从第四行开始
  415. var breakFastTotal, lunchTotal, dinnerTotal, supperTotal, totalTotal float64
  416. var breakFastAmountTotal, lunchAmountTotal, dinnerAmountTotal, supperAmountTotal, totalAmountTotal float64
  417. for _, device := range deviceNameArr {
  418. for kk, vv := range v {
  419. if kk == "" {
  420. kk = k
  421. }
  422. if device == kk {
  423. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{kk,
  424. vv["早餐"]["num"], vv["早餐"]["amount"],
  425. vv["午餐"]["num"], vv["午餐"]["amount"],
  426. vv["晚餐"]["num"], vv["晚餐"]["amount"],
  427. vv["夜宵"]["num"], vv["夜宵"]["amount"],
  428. vv["合计"]["num"], vv["合计"]["amount"],
  429. })
  430. breakFastTotal += vv["早餐"]["num"]
  431. lunchTotal += vv["午餐"]["num"]
  432. dinnerTotal += vv["晚餐"]["num"]
  433. supperTotal += vv["夜宵"]["num"]
  434. totalTotal += vv["合计"]["num"]
  435. breakFastAmountTotal += vv["早餐"]["amount"]
  436. lunchAmountTotal += vv["午餐"]["amount"]
  437. dinnerAmountTotal += vv["晚餐"]["amount"]
  438. supperAmountTotal += vv["夜宵"]["amount"]
  439. totalAmountTotal += vv["合计"]["amount"]
  440. j++
  441. }
  442. }
  443. }
  444. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{"合计",
  445. breakFastTotal, breakFastAmountTotal,
  446. lunchTotal, lunchAmountTotal,
  447. dinnerTotal, dinnerAmountTotal,
  448. supperTotal, supperAmountTotal,
  449. totalTotal, totalAmountTotal,
  450. })
  451. sheetIndex++
  452. }
  453. xlsx.DeleteSheet("template") //删除模板表
  454. //将文件保存至服务器
  455. xlsx.SaveAs("./static" + downloadPath)
  456. break
  457. case 3:
  458. //就餐数据统计表
  459. xlsx, _ := excelize.OpenFile("./static/template/自营学校(就餐数据统计表).xlsx")
  460. fileName = "就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  461. downloadPath = "/export/self_support_for_school/" + fileName
  462. //查询出所有的设备
  463. //var deviceList []*model.Device
  464. //err := db.Db.Where("enterprise_id != 0").Find(&deviceList)
  465. //if err != nil {
  466. // logx.Error(err)
  467. // println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>1111Error:::", err.Error())
  468. // return
  469. //}
  470. //var deviceListMapping = map[string]model.Device{}
  471. //for _, v := range deviceList {
  472. // deviceListMapping[v.DeviceSn] = *v
  473. //}
  474. var m []*db.SelfSupportForSchoolOrdWithUserIdentity
  475. sess := db.Db.Desc("self_support_for_school_ord.id")
  476. if req.EnterpriseId != 0 {
  477. sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
  478. }
  479. if req.StartDate != "" {
  480. sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
  481. }
  482. if req.EndDate != "" {
  483. sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
  484. }
  485. if req.EnterPriseKind != 0 {
  486. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  487. }
  488. _, err := sess.
  489. Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id").
  490. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  491. Join("LEFT", "user", "user.id = user_identity.uid").
  492. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  493. Join("LEFT", "class", "class_with_user.class_id = class.id").
  494. Join("LEFT", "grade", "class.grade_id = grade.id").
  495. FindAndCount(&m)
  496. if err != nil {
  497. logx.Error(err)
  498. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  499. return
  500. }
  501. //整合数据
  502. var data = map[string]map[string]map[string]map[string]float64{}
  503. date1, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  504. if err != nil {
  505. logx.Error(err)
  506. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  507. return
  508. }
  509. date2, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  510. if err != nil {
  511. logx.Error(err)
  512. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  513. return
  514. }
  515. diffDays := int(date2.Sub(date1).Hours() / 24)
  516. var dates []string
  517. for i := 0; i <= diffDays; i++ {
  518. date := date1.AddDate(0, 0, i)
  519. shopName := date.Format("2006-01-02")
  520. dates = append(dates, shopName)
  521. for _, vv := range m {
  522. tmpDate, err1 := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.FaceTime, time.Local)
  523. if err1 != nil {
  524. logx.Error(err1)
  525. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  526. return
  527. }
  528. fmt.Println(tmpDate.Format("2006-01-02"))
  529. if shopName == tmpDate.Format("2006-01-02") {
  530. if data[vv.Enterprise.Name] == nil {
  531. data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  532. }
  533. if data[vv.Enterprise.Name][shopName] == nil {
  534. data[vv.Enterprise.Name][shopName] = make(map[string]map[string]float64)
  535. }
  536. mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime)
  537. if data[vv.Enterprise.Name][shopName][mealZh] == nil {
  538. data[vv.Enterprise.Name][shopName][mealZh] = make(map[string]float64)
  539. }
  540. if data[vv.Enterprise.Name][shopName]["合计"] == nil {
  541. data[vv.Enterprise.Name][shopName]["合计"] = make(map[string]float64)
  542. }
  543. data[vv.Enterprise.Name][shopName][mealZh]["num"]++
  544. data[vv.Enterprise.Name][shopName][mealZh]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  545. data[vv.Enterprise.Name][shopName]["合计"]["num"]++
  546. data[vv.Enterprise.Name][shopName]["合计"]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  547. }
  548. }
  549. }
  550. xlsx.SetSheetRow("", "A1", &titleList)
  551. sheetIndex := 2 //第一个表是模板表
  552. for k, v := range data {
  553. if k == "" {
  554. k = "未知"
  555. }
  556. xlsx.NewSheet(k) //1、新建表格
  557. xlsx.CopySheet(1, sheetIndex)
  558. j := 4 //表头前三行被占用了,只能从第四行开始
  559. for _, date := range dates {
  560. for kk, vv := range v {
  561. if date == kk {
  562. xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{kk,
  563. vv["早餐"]["num"], vv["早餐"]["amount"],
  564. vv["午餐"]["num"], vv["午餐"]["amount"],
  565. vv["晚餐"]["num"], vv["晚餐"]["amount"],
  566. vv["夜宵"]["num"], vv["夜宵"]["amount"],
  567. vv["合计"]["num"], vv["合计"]["amount"],
  568. })
  569. j++
  570. }
  571. sheetIndex++
  572. }
  573. }
  574. }
  575. xlsx.DeleteSheet("template") //删除模板表
  576. //将文件保存至服务器
  577. xlsx.SaveAs("./static" + downloadPath)
  578. break
  579. case 4:
  580. //设备就餐数据统计表
  581. fileName = "设备就餐数据统计_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  582. downloadPath = "/export/self_support_for_school/" + fileName
  583. //查询出所有的设备
  584. var deviceList []*model.Device
  585. if req.EnterpriseId == 0 {
  586. err := db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
  587. if err != nil {
  588. logx.Error(err)
  589. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>1111Error:::", err.Error())
  590. return
  591. }
  592. } else {
  593. err := db.Db.Where("enterprise_id = ?", req.EnterpriseId).OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
  594. if err != nil {
  595. logx.Error(err)
  596. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>1111Error:::", err.Error())
  597. return
  598. }
  599. }
  600. date1, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  601. if err != nil {
  602. logx.Error(err)
  603. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  604. return
  605. }
  606. date2, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  607. if err != nil {
  608. logx.Error(err)
  609. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  610. return
  611. }
  612. diffDays := int(date2.Sub(date1).Hours() / 24)
  613. var deviceListMapping = map[string]model.Device{}
  614. //整合数据
  615. var data = map[string]map[string]map[string]map[string]float64{}
  616. var xlsFileName, xlsDownloadPath []string
  617. for _, v := range deviceList {
  618. deviceListMapping[v.DeviceSn] = *v
  619. var m []*db.SelfSupportForSchoolOrdWithUserIdentityV2
  620. sess := db.Db.Where("device_sn = ?", v.DeviceSn).And("enterprise_id =?", req.EnterpriseId).Desc("self_support_for_school_ord.id")
  621. if req.EnterpriseId != 0 {
  622. sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
  623. }
  624. if req.StartDate != "" {
  625. sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
  626. }
  627. if req.EndDate != "" {
  628. sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
  629. }
  630. _, err = sess.Join("LEFT", "enterprise", "self_support_for_school_ord.enterprise_id = enterprise.id").FindAndCount(&m)
  631. if err != nil {
  632. logx.Error(err)
  633. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  634. return
  635. }
  636. for _, vv := range m {
  637. tmpTime, err1 := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.FaceTime, time.Local)
  638. if err1 != nil {
  639. logx.Error(err1)
  640. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  641. return
  642. }
  643. tmpDate := tmpTime.Format("2006-01-02")
  644. if data[vv.Enterprise.Name] == nil {
  645. data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  646. }
  647. if data[vv.Enterprise.Name][v.Name] == nil {
  648. data[vv.Enterprise.Name][v.Name] = make(map[string]map[string]float64)
  649. }
  650. if data[vv.Enterprise.Name][v.Name][tmpDate] == nil {
  651. data[vv.Enterprise.Name][v.Name][tmpDate] = make(map[string]float64)
  652. }
  653. data[vv.Enterprise.Name][v.Name][tmpDate]["num"]++
  654. data[vv.Enterprise.Name][v.Name][tmpDate]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
  655. }
  656. }
  657. for k1, v := range data {
  658. tmpFileName := k1 + "设备就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  659. tmpDownloadPath := "./static/export/self_support_for_school/" + tmpFileName
  660. xlsx := excelize.NewFile()
  661. var totalData = map[string]map[string]float64{}
  662. for _, device := range deviceList {
  663. for k2, vv := range v {
  664. if k2 == device.Name {
  665. var sumNum, sumAmount = float64(0), float64(0)
  666. xlsx.NewSheet(k2)
  667. titleList = []string{" 设 备 分 餐 数 据 统 计 表 "}
  668. xlsx.SetSheetRow(k2, "A1", &titleList)
  669. titleList = []string{"日 期", "消费笔数", "消费金额"}
  670. xlsx.SetSheetRow(k2, "A2", &titleList)
  671. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  672. if err != nil {
  673. logx.Error(err)
  674. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  675. panic(err)
  676. }
  677. xlsx.MergeCell(k2, "A1", "C1") //合并单元格
  678. xlsx.SetCellStyle(k2, "A1", "C1", style)
  679. xlsx.SetColWidth(k2, "A", "C", 20)
  680. j := 3 //表头前两行用了,只能从第三行开始
  681. for i := 0; i <= diffDays; i++ {
  682. date := date1.AddDate(0, 0, i).Format("2006-01-02")
  683. if vv[date] != nil {
  684. xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{date, vv[date]["num"], vv[date]["amount"]})
  685. sumNum += vv[date]["num"]
  686. sumAmount += vv[date]["amount"]
  687. } else {
  688. xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{date, 0, 0})
  689. }
  690. j++
  691. }
  692. xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{
  693. "合计", sumNum, sumAmount})
  694. if totalData[k2] == nil {
  695. totalData[k2] = map[string]float64{}
  696. }
  697. totalData[k2]["num"] = sumNum
  698. totalData[k2]["amount"] = sumAmount
  699. }
  700. }
  701. }
  702. //xlsx.NewSheet("所有档口")
  703. xlsx.SetSheetName("Sheet1", "所有档口")
  704. titleList = []string{" 设 备 分 餐 数 据 统 计 表 "}
  705. xlsx.SetSheetRow("所有档口", "A1", &titleList)
  706. titleList = []string{"名 称", "消费笔数", "消费金额"}
  707. xlsx.SetSheetRow("所有档口", "A2", &titleList)
  708. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  709. if err != nil {
  710. logx.Error(err)
  711. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  712. panic(err)
  713. }
  714. xlsx.MergeCell("所有档口", "A1", "C1") //合并单元格
  715. xlsx.SetCellStyle("所有档口", "A1", "C1", style)
  716. xlsx.SetColWidth("所有档口", "A", "C", 20)
  717. j := 3 //表头前两行用了,只能从第三行开始
  718. var totalNum, totalAmount float64
  719. for _, device := range deviceList {
  720. for key, val := range totalData {
  721. if key == device.Name {
  722. totalNum += val["num"]
  723. totalAmount += val["amount"]
  724. xlsx.SetSheetRow("所有档口", "A"+strconv.Itoa(j), &[]interface{}{key, val["num"], val["amount"]})
  725. j++
  726. }
  727. }
  728. }
  729. xlsx.SetSheetRow("所有档口", "A"+strconv.Itoa(j), &[]interface{}{"合计", totalNum, totalAmount})
  730. //xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  731. //将文件保存至服务器
  732. err1 := xlsx.SaveAs(tmpDownloadPath)
  733. if err1 != nil {
  734. logx.Error(err1)
  735. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  736. panic(err1)
  737. }
  738. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  739. xlsFileName = append(xlsFileName, tmpFileName)
  740. }
  741. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  742. if err != nil {
  743. logx.Error(err)
  744. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  745. panic(err)
  746. }
  747. defer archive.Close()
  748. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  749. for k, v := range xlsDownloadPath {
  750. w, err1 := zipWriter.Create("设备就餐数据统计/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  751. if err1 != nil {
  752. logx.Error(err1)
  753. println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  754. panic(err1)
  755. }
  756. f, err1 := os.Open(v) //打开待压缩的文件
  757. if err1 != nil {
  758. logx.Error(err1)
  759. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  760. panic(err1)
  761. }
  762. if _, err1 = io.Copy(w, f); err != nil {
  763. logx.Error(err1)
  764. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  765. panic(err1)
  766. }
  767. if err1 != nil {
  768. logx.Error(err1)
  769. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  770. panic(err1)
  771. }
  772. f.Close()
  773. os.RemoveAll(v) //TODO::移除源文件
  774. }
  775. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  776. if err != nil {
  777. panic(err)
  778. }
  779. break
  780. }
  781. //新增数据
  782. selfSupportForSchoolExportRecordsDb := db.SelfSupportForSchoolExportRecordsDb{}
  783. selfSupportForSchoolExportRecordsDb.Set()
  784. marshal, _ := json.Marshal(req)
  785. selfSupportForSchoolExportRecordsDb.SelfSupportForSchoolExportRecordsInsert(&model.SelfSupportForSchoolExportRecords{
  786. Name: fileName,
  787. DownloadPath: downloadPath,
  788. Kind: req.Kind,
  789. ReqContent: string(marshal),
  790. CreateAt: now.Format("2006-01-02 15:04:05"),
  791. UpdateAt: now.Format("2006-01-02 15:04:05"),
  792. })
  793. }
  794. func CentralKitchenForSchoolDataStatisticsExport(req md.CentralKitchenForSchoolDataStatisticsExportReq) {
  795. var titleList []string
  796. var fileName, downloadPath string
  797. var now = time.Now()
  798. for _, kind := range req.Kinds {
  799. switch kind {
  800. case 1:
  801. xlsx := excelize.NewFile()
  802. //订单列表
  803. fileName = "订单列表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  804. downloadPath = "/export/central_kitchen_for_school/" + fileName
  805. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  806. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  807. //查找订单数据
  808. sess := db.Db.Desc("central_kitchen_for_school_package_ord.id")
  809. sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess)
  810. if req.EnterpriseId != 0 {
  811. sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId)
  812. }
  813. if req.StartDate != "" {
  814. sess.And("central_kitchen_for_school_package_ord.create_at >= ?", req.StartDate)
  815. }
  816. if req.EndDate != "" {
  817. sess.And("central_kitchen_for_school_package_ord.create_at <= ?", req.EndDate)
  818. }
  819. if req.EnterPriseKind != 0 {
  820. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  821. }
  822. var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity
  823. _, err := sess.
  824. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  825. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  826. Join("LEFT", "user", "user.id = user_identity.uid").
  827. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  828. Join("LEFT", "class", "class_with_user.class_id = class.id").
  829. Join("LEFT", "grade", "class.grade_id = grade.id").
  830. FindAndCount(&m)
  831. if err != nil {
  832. logx.Error(err)
  833. println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
  834. return
  835. }
  836. //查找预定数据
  837. var outTradeNoList []string
  838. for _, v := range m {
  839. outTradeNoList = append(outTradeNoList, v.OutTradeNo)
  840. }
  841. var mm []model.CentralKitchenForSchoolPackageOrdForReserve
  842. sess1 := db.Db.Desc("id")
  843. if req.EnterpriseId != 0 {
  844. sess1.And("enterprise_id = ?", req.EnterpriseId)
  845. }
  846. if len(req.MealKindList) > 0 {
  847. sess1.In("kind", req.MealKindList)
  848. }
  849. err = sess1.In("out_trade_no", outTradeNoList).Find(&mm)
  850. if err != nil {
  851. logx.Error(err)
  852. println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
  853. return
  854. }
  855. var exportOutTradeNoList []string
  856. for _, v := range mm {
  857. exportOutTradeNoList = append(exportOutTradeNoList, v.OutTradeNo)
  858. }
  859. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 订单表"}
  860. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  861. titleList = []string{"订单号", "学生姓名", "学校", "年级", "班级", "家长电话", "预定日期", "预定餐数", "订单价格", "支付时间", "订单状态"}
  862. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  863. xlsx.MergeCell("Sheet1", "A1", "K1") //合并单元格
  864. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  865. if err != nil {
  866. logx.Error(err)
  867. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  868. panic(err)
  869. }
  870. xlsx.SetCellStyle("Sheet1", "A1", "K1", style)
  871. xlsx.SetColWidth("Sheet1", "A", "k", 20)
  872. j := 3 //表头前两行用了,只能从第三行开始
  873. for _, v := range m {
  874. if !utils.InArr(v.OutTradeNo, exportOutTradeNoList) {
  875. continue
  876. }
  877. var ordState string //订单状态(0:待支付 1:预约成功 2:退款中 3:部分退款 4:已退款 5:已完成)
  878. switch v.CentralKitchenForSchoolPackageOrd.OrdState {
  879. case enum.CentralKitchenForSchoolPackageOrdOrdStateForWait:
  880. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForWait)
  881. break
  882. case enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess:
  883. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess)
  884. break
  885. case enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding:
  886. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding)
  887. break
  888. case enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded:
  889. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded)
  890. break
  891. case enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded:
  892. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded)
  893. break
  894. case enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete:
  895. ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete)
  896. break
  897. }
  898. //预定餐数、预定日期
  899. var list []*model.CentralKitchenForSchoolUserWithDay
  900. err1 := json.Unmarshal([]byte(v.CentralKitchenForSchoolPackageOrd.WithDayData), &list)
  901. if err1 != nil {
  902. logx.Error(err)
  903. println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
  904. return
  905. }
  906. var reserveDays string
  907. for _, v1 := range list {
  908. reserveDays += v1.Date + ", "
  909. }
  910. if v.Grade.Name == "" {
  911. v.Grade.Name = "教师"
  912. }
  913. if v.Class.Name == "" {
  914. v.Class.Name = "教师"
  915. }
  916. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.CentralKitchenForSchoolPackageOrd.OutTradeNo, v.CentralKitchenForSchoolPackageOrd.UserIdentityName, v.Enterprise.Name,
  917. v.Grade.Name, v.Class.Name, v.User.Phone, reserveDays, len(list), v.CentralKitchenForSchoolPackageOrd.TotalPrice, v.CentralKitchenForSchoolPackageOrd.CreateAt, ordState})
  918. j++
  919. }
  920. //将文件保存至服务器
  921. xlsx.SaveAs("./static" + downloadPath)
  922. break
  923. case 2:
  924. xlsx := excelize.NewFile()
  925. //退款申请表
  926. fileName = "退款申请表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  927. downloadPath = "/export/central_kitchen_for_school/" + fileName
  928. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  929. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  930. //查找退款申请数据
  931. sess := db.Db.Desc("central_kitchen_for_school_user_refund_day.id")
  932. if req.EnterpriseId != 0 {
  933. sess.And("enterprise.id =?", req.EnterpriseId)
  934. }
  935. if req.StartDate != "" {
  936. sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
  937. }
  938. if req.EndDate != "" {
  939. sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
  940. }
  941. if len(req.MealKindList) > 0 {
  942. sess.In("central_kitchen_for_school_user_with_day.kind", req.MealKindList)
  943. }
  944. if req.EnterPriseKind != 0 {
  945. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  946. }
  947. var m []*db.CentralKitchenForSchoolUserRefundDayWithData
  948. _, err := sess.
  949. 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").
  950. 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").
  951. Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
  952. Join("LEFT", "user", "user_identity.uid = user.id").
  953. Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
  954. Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
  955. Join("LEFT", "class", "class_with_user.class_id = class.id").
  956. Join("LEFT", "grade", "class.grade_id = grade.id").
  957. Desc("central_kitchen_for_school_user_refund_day.id").
  958. FindAndCount(&m)
  959. if err != nil {
  960. logx.Error(err)
  961. println("<<<<CentralKitchenForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
  962. return
  963. }
  964. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 退款申请表"}
  965. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  966. titleList = []string{"学生姓名", "学校", "年级", "班级", "家长电话", "退款日期", "餐型", "退款金额", "退款状态", "支付时间", "退款操作时间"}
  967. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  968. xlsx.MergeCell("Sheet1", "A1", "K1") //合并单元格
  969. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  970. if err != nil {
  971. logx.Error(err)
  972. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  973. panic(err)
  974. }
  975. xlsx.SetCellStyle("Sheet1", "A1", "K1", style)
  976. xlsx.SetColWidth("Sheet1", "A", "k", 20)
  977. j := 3 //表头前两行用了,只能从第三行开始
  978. for _, v := range m {
  979. var kind string //就餐类型(1:早餐 2:午餐 3:晚餐)
  980. switch v.CentralKitchenForSchoolUserWithDay.Kind {
  981. case enum.CentralKitchenForSchoolUserWithDayKindForBreakfast:
  982. kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast)
  983. break
  984. case enum.CentralKitchenForSchoolUserWithDayKindForLunch:
  985. kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch)
  986. break
  987. case enum.CentralKitchenForSchoolUserWithDayKindForDinner:
  988. kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner)
  989. break
  990. }
  991. var state string //状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成)
  992. switch v.CentralKitchenForSchoolUserRefundDay.State {
  993. case enum.CentralKitchenForSchoolUserRefundDayStateForAuditing:
  994. state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditing)
  995. break
  996. case enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass:
  997. state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass)
  998. break
  999. case enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject:
  1000. state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject)
  1001. break
  1002. case enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete:
  1003. state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete)
  1004. break
  1005. }
  1006. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.CentralKitchenForSchoolPackageOrd.UserIdentityName, v.Enterprise.Name, v.Grade.Name, v.Class.Name, v.User.Phone,
  1007. v.CentralKitchenForSchoolUserWithDay.Date, kind, v.CentralKitchenForSchoolUserRefundDay.Amount, state, v.CentralKitchenForSchoolPackageOrd.CreateAt, v.CentralKitchenForSchoolUserRefundDay.RefundDate})
  1008. j++
  1009. }
  1010. //将文件保存至服务器
  1011. xlsx.SaveAs("./static" + downloadPath)
  1012. break
  1013. case 3:
  1014. //学校预定统计表
  1015. fileName = "学校预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1016. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1017. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  1018. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  1019. if req.EnterpriseId != 0 {
  1020. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  1021. }
  1022. var months []time.Month
  1023. if req.StartDate != "" {
  1024. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1025. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1026. _, sMonth, _ := sDate.Date()
  1027. _, eMonth, _ := eDate.Date()
  1028. diffMonth := sMonth - eMonth
  1029. if diffMonth == 0 {
  1030. //TODO::查询一个月
  1031. months = append(months, sMonth)
  1032. } else {
  1033. for i := sMonth; i <= eMonth; i++ {
  1034. months = append(months, i)
  1035. }
  1036. }
  1037. }
  1038. if len(months) > 0 {
  1039. sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
  1040. }
  1041. //if req.EndDate != "" {
  1042. // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
  1043. //}
  1044. if len(req.MealKindList) > 0 {
  1045. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  1046. }
  1047. if req.EnterPriseKind != 0 {
  1048. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1049. }
  1050. _, err := sess.
  1051. 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").
  1052. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1053. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1054. Join("LEFT", "user", "user.id = user_identity.uid").
  1055. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  1056. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1057. Join("LEFT", "grade", "class.grade_id = grade.id").
  1058. FindAndCount(&m)
  1059. if err != nil {
  1060. logx.Error(err)
  1061. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1062. return
  1063. }
  1064. var ordNoArr, mealKindListArr []string
  1065. for _, v := range m {
  1066. ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
  1067. }
  1068. 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`"
  1069. for _, v := range req.MealKindList {
  1070. mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
  1071. }
  1072. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1073. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1074. nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
  1075. nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
  1076. var nativeResultsMap = map[string]map[int]int64{}
  1077. for _, v := range nativeResults {
  1078. if nativeResultsMap[v["ord_no"]] == nil {
  1079. nativeResultsMap[v["ord_no"]] = make(map[int]int64)
  1080. }
  1081. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"])
  1082. }
  1083. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  1084. centralKitchenForSchoolUserWithDayDb.Set(0)
  1085. var list = map[string]map[string]map[string]map[string]int64{}
  1086. var xlsFileName, xlsDownloadPath []string
  1087. for _, v := range m {
  1088. if list[v.Enterprise.Name] == nil {
  1089. list[v.Enterprise.Name] = make(map[string]map[string]map[string]int64)
  1090. }
  1091. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1092. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]int64)
  1093. }
  1094. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1095. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]int64)
  1096. }
  1097. //count, err2 := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByOrdNo(
  1098. // v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo,
  1099. // enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling,
  1100. // req.StartDate, req.EndDate, []int{v.CentralKitchenForSchoolPackageOrdForReserve.Kind})
  1101. //if err2 != nil {
  1102. // logx.Error(err)
  1103. // println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1104. // return
  1105. //}
  1106. //time.Sleep(2 * time.Millisecond) // 2毫秒
  1107. //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  1108. // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["breakfast"] += count
  1109. //}
  1110. //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  1111. // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["lunch"] += count
  1112. //}
  1113. //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  1114. // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["dinner"] += count
  1115. //}
  1116. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  1117. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["breakfast"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
  1118. }
  1119. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  1120. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["lunch"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
  1121. }
  1122. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  1123. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["dinner"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
  1124. }
  1125. }
  1126. for k1, v1 := range list {
  1127. xlsx := excelize.NewFile()
  1128. tmpFileName := k1 + "学校预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1129. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1130. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1131. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1132. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") "}
  1133. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1134. titleList = []string{"年级", "班级", "早餐", "午餐", "晚餐"}
  1135. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1136. xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
  1137. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1138. if err != nil {
  1139. logx.Error(err)
  1140. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1141. panic(err)
  1142. }
  1143. xlsx.SetCellStyle("Sheet1", "A1", "E1", style)
  1144. xlsx.SetColWidth("Sheet1", "A", "E", 20)
  1145. j := 3 //表头前两行用了,只能从第三行开始
  1146. var sumClassNum, sumBreakfast, sumLunch, sumDinner = int64(0), int64(0), int64(0), int64(0)
  1147. tmpEnterpriseDb := db.EnterpriseDb{}
  1148. tmpEnterpriseDb.Set()
  1149. tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
  1150. if err11 != nil {
  1151. logx.Error(err11)
  1152. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err11.Error())
  1153. panic(err11)
  1154. }
  1155. tmpClassDb := db.ClassDb{}
  1156. tmpClassDb.Set(0)
  1157. classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
  1158. if err != nil {
  1159. logx.Error(err)
  1160. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1161. panic(err)
  1162. }
  1163. for _, class := range *classList {
  1164. for k2, v2 := range v1 {
  1165. if k2 == "" {
  1166. //若年级为空,则为教师餐
  1167. k2 = "教师餐"
  1168. }
  1169. for k3, v3 := range v2 {
  1170. if class.Name != k3 {
  1171. continue
  1172. }
  1173. if k3 == "" {
  1174. //若班级为空,则为教师餐
  1175. k3 = "教师餐"
  1176. }
  1177. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
  1178. k2, k3, v3["breakfast"], v3["lunch"], v3["dinner"]})
  1179. sumClassNum++
  1180. sumBreakfast += v3["breakfast"]
  1181. sumLunch += v3["lunch"]
  1182. sumDinner += v3["dinner"]
  1183. j++
  1184. }
  1185. }
  1186. }
  1187. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
  1188. "合计", sumClassNum, sumBreakfast, sumLunch, sumDinner})
  1189. //将文件保存至服务器
  1190. err1 := xlsx.SaveAs(tmpDownloadPath)
  1191. if err1 != nil {
  1192. logx.Error(err1)
  1193. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1194. panic(err1)
  1195. }
  1196. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1197. xlsFileName = append(xlsFileName, tmpFileName)
  1198. }
  1199. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1200. if err != nil {
  1201. logx.Error(err)
  1202. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1203. panic(err)
  1204. }
  1205. defer archive.Close()
  1206. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1207. for k, v := range xlsDownloadPath {
  1208. w, err1 := zipWriter.Create("学校预定统计/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1209. if err1 != nil {
  1210. logx.Error(err1)
  1211. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1212. panic(err1)
  1213. }
  1214. f, err1 := os.Open(v) //打开待压缩的文件
  1215. if err1 != nil {
  1216. logx.Error(err1)
  1217. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1218. panic(err1)
  1219. }
  1220. if _, err1 = io.Copy(w, f); err != nil {
  1221. logx.Error(err1)
  1222. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1223. panic(err1)
  1224. }
  1225. if err1 != nil {
  1226. logx.Error(err1)
  1227. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
  1228. panic(err1)
  1229. }
  1230. f.Close()
  1231. os.RemoveAll(v) //TODO::移除源文件
  1232. }
  1233. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1234. if err != nil {
  1235. panic(err)
  1236. }
  1237. break
  1238. case 4:
  1239. //班级明细表
  1240. fileName = "班级明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1241. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1242. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  1243. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  1244. if req.EnterpriseId != 0 {
  1245. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  1246. }
  1247. var months []time.Month
  1248. if req.StartDate != "" {
  1249. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1250. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1251. _, sMonth, _ := sDate.Date()
  1252. _, eMonth, _ := eDate.Date()
  1253. diffMonth := sMonth - eMonth
  1254. if diffMonth == 0 {
  1255. //TODO::查询一个月
  1256. months = append(months, sMonth)
  1257. } else {
  1258. for i := sMonth; i <= eMonth; i++ {
  1259. months = append(months, i)
  1260. }
  1261. }
  1262. }
  1263. if len(months) > 0 {
  1264. sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
  1265. }
  1266. //if req.EndDate != "" {
  1267. // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
  1268. //}
  1269. if len(req.MealKindList) > 0 {
  1270. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  1271. }
  1272. if req.EnterPriseKind != 0 {
  1273. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1274. }
  1275. _, err := sess.
  1276. 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").
  1277. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1278. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1279. Join("LEFT", "user", "user.id = user_identity.uid").
  1280. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  1281. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1282. Join("LEFT", "grade", "class.grade_id = grade.id").
  1283. Asc("class.id").
  1284. FindAndCount(&m)
  1285. if err != nil {
  1286. logx.Error(err)
  1287. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1288. return
  1289. }
  1290. var ordNoArr, mealKindListArr []string
  1291. for _, v := range m {
  1292. ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
  1293. }
  1294. 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`"
  1295. for _, v := range req.MealKindList {
  1296. mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
  1297. }
  1298. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1299. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1300. nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
  1301. nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
  1302. var nativeResultsMap = map[string]map[int]int64{}
  1303. for _, v := range nativeResults {
  1304. if nativeResultsMap[v["ord_no"]] == nil {
  1305. nativeResultsMap[v["ord_no"]] = make(map[int]int64)
  1306. }
  1307. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"])
  1308. }
  1309. var list = map[string]map[string]map[string]map[string]map[string]int64{}
  1310. var xlsFileName, xlsDownloadPath []string
  1311. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  1312. centralKitchenForSchoolUserWithDayDb.Set(0)
  1313. for _, v := range m {
  1314. if list[v.Enterprise.Name] == nil {
  1315. list[v.Enterprise.Name] = make(map[string]map[string]map[string]map[string]int64)
  1316. }
  1317. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1318. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]map[string]int64)
  1319. }
  1320. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1321. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]map[string]int64)
  1322. }
  1323. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] == nil {
  1324. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = make(map[string]int64)
  1325. }
  1326. //count, err2 := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByOrdNo(
  1327. // v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo,
  1328. // enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling,
  1329. // req.StartDate, req.EndDate, []int{v.CentralKitchenForSchoolPackageOrdForReserve.Kind})
  1330. //if err2 != nil {
  1331. // logx.Error(err2)
  1332. // println("<<<<SelfSupportForSchoolDataStatistics Export3>>>>>Error:::", err2.Error())
  1333. // return
  1334. //}
  1335. //if count == 0 {
  1336. // continue
  1337. //}
  1338. //time.Sleep(2 * time.Millisecond) // 2毫秒
  1339. //
  1340. //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  1341. // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["breakfast"] += count
  1342. //}
  1343. //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  1344. // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["lunch"] += count
  1345. //}
  1346. //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  1347. // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["dinner"] += count
  1348. //}
  1349. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  1350. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["breakfast"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
  1351. }
  1352. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  1353. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["lunch"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
  1354. }
  1355. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  1356. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["dinner"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
  1357. }
  1358. }
  1359. for k1, v1 := range list {
  1360. xlsx := excelize.NewFile()
  1361. tmpFileName := k1 + "班级明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1362. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1363. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1364. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1365. //查询当前学校下的班级升序
  1366. tmpEnterpriseDb := db.EnterpriseDb{}
  1367. tmpEnterpriseDb.Set()
  1368. tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
  1369. if err11 != nil {
  1370. logx.Error(err11)
  1371. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err11.Error())
  1372. panic(err11)
  1373. }
  1374. tmpClassDb := db.ClassDb{}
  1375. tmpClassDb.Set(0)
  1376. classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
  1377. if err != nil {
  1378. logx.Error(err)
  1379. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1380. panic(err)
  1381. }
  1382. for _, class := range *classList {
  1383. for k2, v2 := range v1 {
  1384. if k2 == "" {
  1385. //若年级为空,则为教师餐
  1386. continue
  1387. }
  1388. for k3, v3 := range v2 {
  1389. if class.Name != k3 {
  1390. continue
  1391. }
  1392. xlsx.NewSheet(k3)
  1393. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + ", " + k3 + "] 班级明细"}
  1394. xlsx.SetSheetRow(k3, "A1", &titleList)
  1395. titleList = []string{"姓名", "早餐", "午餐", "晚餐"}
  1396. xlsx.SetSheetRow(k3, "A2", &titleList)
  1397. xlsx.MergeCell(k3, "A1", "D1") //合并单元格
  1398. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1399. if err != nil {
  1400. logx.Error(err)
  1401. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1402. panic(err)
  1403. }
  1404. xlsx.SetCellStyle(k3, "A1", "D1", style)
  1405. xlsx.SetColWidth(k3, "A", "D", 20)
  1406. var sumBreakfast, sumLunch, sumDinner = int64(0), int64(0), int64(0)
  1407. j := 3 //表头前两行用了,只能从第三行开始
  1408. for k4, v4 := range v3 {
  1409. if v4["breakfast"] == 0 && v4["lunch"] == 0 && v4["dinner"] == 0 {
  1410. continue
  1411. }
  1412. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  1413. k4, v4["breakfast"], v4["lunch"], v4["dinner"]})
  1414. sumBreakfast += v4["breakfast"]
  1415. sumLunch += v4["lunch"]
  1416. sumDinner += v4["dinner"]
  1417. j++
  1418. }
  1419. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  1420. "合计", sumBreakfast, sumLunch, sumDinner})
  1421. }
  1422. }
  1423. }
  1424. //将文件保存至服务器
  1425. xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  1426. err1 := xlsx.SaveAs(tmpDownloadPath)
  1427. if err1 != nil {
  1428. logx.Error(err1)
  1429. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1430. panic(err1)
  1431. }
  1432. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1433. xlsFileName = append(xlsFileName, tmpFileName)
  1434. }
  1435. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1436. if err != nil {
  1437. logx.Error(err)
  1438. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  1439. panic(err)
  1440. }
  1441. defer archive.Close()
  1442. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1443. for k, v := range xlsDownloadPath {
  1444. w, err1 := zipWriter.Create("班级明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1445. if err1 != nil {
  1446. logx.Error(err1)
  1447. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1448. panic(err1)
  1449. }
  1450. f, err1 := os.Open(v) //打开待压缩的文件
  1451. if err1 != nil {
  1452. logx.Error(err1)
  1453. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1454. panic(err1)
  1455. }
  1456. if _, err1 = io.Copy(w, f); err != nil {
  1457. logx.Error(err1)
  1458. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1459. panic(err1)
  1460. }
  1461. if err1 != nil {
  1462. logx.Error(err1)
  1463. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
  1464. panic(err1)
  1465. }
  1466. f.Close()
  1467. os.RemoveAll(v) //TODO::移除源文件
  1468. }
  1469. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1470. if err != nil {
  1471. panic(err)
  1472. }
  1473. break
  1474. case 5:
  1475. xlsx := excelize.NewFile()
  1476. //退款明细表
  1477. fileName = "退款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1478. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1479. sess := db.Db.Where("central_kitchen_for_school_user_refund_day.state =?", enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete).Desc("central_kitchen_for_school_user_refund_day.id")
  1480. if req.EnterpriseId != 0 {
  1481. sess.And("enterprise.id =?", req.EnterpriseId)
  1482. }
  1483. if req.StartDate != "" {
  1484. sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
  1485. }
  1486. if req.EndDate != "" {
  1487. sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
  1488. }
  1489. if len(req.MealKindList) > 0 {
  1490. sess.In("central_kitchen_for_school_user_with_day.kind", req.MealKindList)
  1491. }
  1492. if req.EnterPriseKind != 0 {
  1493. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1494. }
  1495. var m []*db.CentralKitchenForSchoolUserRefundDayWithData
  1496. _, err := sess.
  1497. 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").
  1498. 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").
  1499. Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
  1500. Join("LEFT", "user", "user_identity.uid = user.id").
  1501. Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
  1502. Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
  1503. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1504. Join("LEFT", "grade", "class.grade_id = grade.id").
  1505. Desc("central_kitchen_for_school_user_refund_day.id").
  1506. FindAndCount(&m)
  1507. if err != nil {
  1508. logx.Error(err)
  1509. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err.Error())
  1510. return
  1511. }
  1512. var list = map[string]map[string]map[string]map[string]map[string]int{}
  1513. var xlsFileName, xlsDownloadPath []string
  1514. for _, v := range m {
  1515. if list[v.Enterprise.Name] == nil {
  1516. list[v.Enterprise.Name] = make(map[string]map[string]map[string]map[string]int)
  1517. }
  1518. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1519. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]map[string]int)
  1520. }
  1521. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1522. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]map[string]int)
  1523. }
  1524. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] == nil {
  1525. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = make(map[string]int)
  1526. }
  1527. //就餐类型(1:早餐 2:午餐 3:晚餐)
  1528. if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  1529. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["breakfast"]++
  1530. }
  1531. if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  1532. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["lunch"]++
  1533. }
  1534. if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  1535. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["dinner"]++
  1536. }
  1537. }
  1538. for k1, v1 := range list {
  1539. tmpFileName := k1 + "退款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1540. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1541. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1542. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1543. for k2, v2 := range v1 {
  1544. if k2 == "" {
  1545. //若年级为空,则为教师餐
  1546. continue
  1547. }
  1548. for k3, v3 := range v2 {
  1549. xlsx.NewSheet(k3)
  1550. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + ", " + k3 + "] 退款明细"}
  1551. xlsx.SetSheetRow(k3, "A1", &titleList)
  1552. titleList = []string{"姓名", "早餐", "午餐", "晚餐"}
  1553. xlsx.SetSheetRow(k3, "A2", &titleList)
  1554. xlsx.MergeCell(k3, "A1", "D1") //合并单元格
  1555. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1556. if err != nil {
  1557. logx.Error(err)
  1558. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1559. panic(err)
  1560. }
  1561. xlsx.SetCellStyle(k3, "A1", "D1", style)
  1562. xlsx.SetColWidth(k3, "A", "D", 20)
  1563. var sumBreakfast, sumLunch, sumDinner = 0, 0, 0
  1564. j := 3 //表头前两行用了,只能从第三行开始
  1565. for k4, v4 := range v3 {
  1566. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  1567. k4, v4["breakfast"], v4["lunch"], v4["dinner"]})
  1568. sumBreakfast += v4["breakfast"]
  1569. sumLunch += v4["lunch"]
  1570. sumDinner += v4["dinner"]
  1571. j++
  1572. }
  1573. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  1574. "合计", sumBreakfast, sumLunch, sumDinner})
  1575. }
  1576. }
  1577. //将文件保存至服务器
  1578. xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  1579. err1 := xlsx.SaveAs(tmpDownloadPath)
  1580. if err1 != nil {
  1581. logx.Error(err1)
  1582. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1583. panic(err1)
  1584. }
  1585. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1586. xlsFileName = append(xlsFileName, tmpFileName)
  1587. }
  1588. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1589. if err != nil {
  1590. logx.Error(err)
  1591. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err.Error())
  1592. panic(err)
  1593. }
  1594. defer archive.Close()
  1595. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1596. for k, v := range xlsDownloadPath {
  1597. w, err1 := zipWriter.Create("退款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1598. if err1 != nil {
  1599. logx.Error(err1)
  1600. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1601. panic(err1)
  1602. }
  1603. f, err1 := os.Open(v) //打开待压缩的文件
  1604. if err1 != nil {
  1605. logx.Error(err1)
  1606. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1607. panic(err1)
  1608. }
  1609. if _, err1 = io.Copy(w, f); err != nil {
  1610. logx.Error(err1)
  1611. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1612. panic(err1)
  1613. }
  1614. if err1 != nil {
  1615. logx.Error(err1)
  1616. println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
  1617. panic(err1)
  1618. }
  1619. f.Close()
  1620. os.RemoveAll(v) //TODO::移除源文件
  1621. }
  1622. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1623. if err != nil {
  1624. panic(err)
  1625. }
  1626. break
  1627. case 6:
  1628. xlsx := excelize.NewFile()
  1629. //收款统计表
  1630. fileName = "收款统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1631. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1632. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1633. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1634. //查找数据
  1635. var m []model.Enterprise
  1636. sess := db.Db.Desc("id")
  1637. if req.EnterPriseKind != 0 {
  1638. sess.And("kind = ?", req.EnterPriseKind)
  1639. }
  1640. if req.EnterpriseId != 0 {
  1641. sess.And("id = ?", req.EnterpriseId)
  1642. }
  1643. err := sess.Find(&m)
  1644. if err != nil {
  1645. logx.Error(err)
  1646. println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
  1647. return
  1648. }
  1649. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 收款统计表"}
  1650. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1651. titleList = []string{"学校名称", "预定总费用", "退款总计", "实收费用", "预估费率"}
  1652. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1653. xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
  1654. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1655. if err != nil {
  1656. logx.Error(err)
  1657. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1658. panic(err)
  1659. }
  1660. xlsx.SetCellStyle("Sheet1", "A1", "E1", style)
  1661. xlsx.SetColWidth("Sheet1", "A", "E", 20)
  1662. j := 3 //表头前两行用了,只能从第三行开始
  1663. for _, v := range m {
  1664. var income, refund string
  1665. //统计收入
  1666. sql1 := fmt.Sprintf("SELECT sum(total_price) as total FROM central_kitchen_for_school_package_ord where state = 1 and enterprise_id = %d and create_at >= '%s' and create_at < '%s'", v.Id, req.StartDate, req.EndDate)
  1667. mapArr1, err := db.QueryNativeString(db.Db, sql1)
  1668. if err != nil {
  1669. logx.Error(err)
  1670. println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
  1671. return
  1672. }
  1673. if mapArr1 != nil {
  1674. income = mapArr1[0]["total"]
  1675. }
  1676. //统计退款
  1677. //查询出当前学校下所有的学生
  1678. userIdentityDb := db.UserIdentityDb{}
  1679. userIdentityDb.Set(0)
  1680. userIdentities, _ := userIdentityDb.FindUserIdentityForEnterprise(v.Id)
  1681. var userIdentityIds []string
  1682. for _, v := range *userIdentities {
  1683. userIdentityIds = append(userIdentityIds, utils.IntToStr(v.Id))
  1684. }
  1685. if len(userIdentityIds) != 0 {
  1686. userIdentityStr := php2go.Implode(",", userIdentityIds)
  1687. 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'",
  1688. enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete, userIdentityStr, req.StartDate, req.EndDate)
  1689. mapArr2, err := db.QueryNativeString(db.Db, sql2)
  1690. if err != nil {
  1691. logx.Error(err)
  1692. println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
  1693. return
  1694. }
  1695. if mapArr2 != nil {
  1696. refund = mapArr2[0]["total"]
  1697. }
  1698. }
  1699. realityAmount := utils.StrToFloat64(income) - utils.StrToFloat64(refund)
  1700. rateFee := realityAmount * 0.0038
  1701. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.Name, income, refund, realityAmount, rateFee})
  1702. j++
  1703. }
  1704. //将文件保存至服务器
  1705. xlsx.SaveAs("./static" + downloadPath)
  1706. break
  1707. case 7:
  1708. xlsx := excelize.NewFile()
  1709. //班级收款明细表
  1710. fileName = "班级收款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1711. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1712. //查找订单数据
  1713. sess := db.Db.Desc("central_kitchen_for_school_package_ord.id")
  1714. sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess).And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent)
  1715. if req.EnterpriseId != 0 {
  1716. sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId)
  1717. }
  1718. if req.StartDate != "" {
  1719. sess.And("central_kitchen_for_school_package_ord.create_at >= ?", req.StartDate)
  1720. }
  1721. if req.EndDate != "" {
  1722. sess.And("central_kitchen_for_school_package_ord.create_at <= ?", req.EndDate)
  1723. }
  1724. if req.EnterPriseKind != 0 {
  1725. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1726. }
  1727. var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity
  1728. _, err := sess.
  1729. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1730. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1731. Join("LEFT", "user", "user.id = user_identity.uid").
  1732. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  1733. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1734. Join("LEFT", "grade", "class.grade_id = grade.id").
  1735. FindAndCount(&m)
  1736. if err != nil {
  1737. logx.Error(err)
  1738. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1739. return
  1740. }
  1741. 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")
  1742. if req.EnterpriseId != 0 {
  1743. sess1.And("enterprise.id =?", req.EnterpriseId)
  1744. }
  1745. if req.StartDate != "" {
  1746. sess1.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
  1747. }
  1748. if req.EndDate != "" {
  1749. sess1.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
  1750. }
  1751. var mm []*db.CentralKitchenForSchoolUserRefundDayWithData
  1752. _, err = sess1.
  1753. 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").
  1754. 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").
  1755. Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
  1756. Join("LEFT", "user", "user_identity.uid = user.id").
  1757. Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
  1758. Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
  1759. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1760. Join("LEFT", "grade", "class.grade_id = grade.id").
  1761. Desc("central_kitchen_for_school_user_refund_day.id").
  1762. FindAndCount(&mm)
  1763. if err != nil {
  1764. logx.Error(err)
  1765. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1766. return
  1767. }
  1768. var list = map[string]map[string]map[string]map[string]float64{}
  1769. for _, v := range m {
  1770. if list[v.Enterprise.Name] == nil {
  1771. list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  1772. }
  1773. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1774. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64)
  1775. }
  1776. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1777. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64)
  1778. }
  1779. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["income"] += utils.StrToFloat64(v.CentralKitchenForSchoolPackageOrd.TotalPrice)
  1780. }
  1781. for _, v := range mm {
  1782. if list[v.Enterprise.Name] == nil {
  1783. list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  1784. }
  1785. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1786. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64)
  1787. }
  1788. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1789. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64)
  1790. }
  1791. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["refund"] += utils.StrToFloat64(v.CentralKitchenForSchoolUserRefundDay.Amount)
  1792. }
  1793. var xlsFileName, xlsDownloadPath []string
  1794. for k1, v1 := range list {
  1795. tmpFileName := k1 + "班级收款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1796. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1797. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1798. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1799. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") 班级收款明细"}
  1800. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1801. titleList = []string{"年级", "班级", "预定总费用", "退款总计"}
  1802. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1803. xlsx.MergeCell("Sheet1", "A1", "D1") //合并单元格
  1804. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1805. if err != nil {
  1806. logx.Error(err)
  1807. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1808. panic(err)
  1809. }
  1810. xlsx.SetCellStyle("Sheet1", "A1", "D1", style)
  1811. xlsx.SetColWidth("Sheet1", "A", "D", 20)
  1812. j := 3 //表头前两行用了,只能从第三行开始
  1813. var sumClassNum = int64(0)
  1814. var sumIncome, sumRefund = float64(0), float64(0)
  1815. for k2, v2 := range v1 {
  1816. if k2 == "" {
  1817. //若年级为空,则为教师餐
  1818. continue
  1819. }
  1820. for k3, v3 := range v2 {
  1821. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{k2, k3, utils.Float64ToStr(v3["income"]), utils.Float64ToStr(v3["refund"])})
  1822. sumClassNum++
  1823. sumIncome += v3["income"]
  1824. sumRefund += v3["refund"]
  1825. j++
  1826. }
  1827. }
  1828. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
  1829. "合计", sumClassNum, sumIncome, sumRefund})
  1830. //将文件保存至服务器
  1831. err1 := xlsx.SaveAs(tmpDownloadPath)
  1832. if err1 != nil {
  1833. logx.Error(err1)
  1834. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1835. panic(err1)
  1836. }
  1837. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1838. xlsFileName = append(xlsFileName, tmpFileName)
  1839. }
  1840. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1841. if err != nil {
  1842. logx.Error(err)
  1843. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1844. panic(err)
  1845. }
  1846. defer archive.Close()
  1847. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1848. for k, v := range xlsDownloadPath {
  1849. w, err1 := zipWriter.Create("班级收款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1850. if err1 != nil {
  1851. logx.Error(err1)
  1852. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1853. panic(err1)
  1854. }
  1855. f, err1 := os.Open(v) //打开待压缩的文件
  1856. if err1 != nil {
  1857. logx.Error(err1)
  1858. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1859. panic(err1)
  1860. }
  1861. if _, err1 = io.Copy(w, f); err != nil {
  1862. logx.Error(err1)
  1863. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1864. panic(err1)
  1865. }
  1866. if err1 != nil {
  1867. logx.Error(err1)
  1868. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1869. panic(err1)
  1870. }
  1871. f.Close()
  1872. os.RemoveAll(v) //TODO::移除源文件
  1873. }
  1874. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1875. if err != nil {
  1876. panic(err)
  1877. }
  1878. break
  1879. case 8:
  1880. xlsx := excelize.NewFile()
  1881. //学校预定数量统计表
  1882. fileName = "学校预定数量统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1883. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1884. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1885. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1886. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  1887. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  1888. if req.EnterpriseId != 0 {
  1889. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  1890. }
  1891. var months []time.Month
  1892. if req.StartDate != "" {
  1893. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1894. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1895. _, sMonth, _ := sDate.Date()
  1896. _, eMonth, _ := eDate.Date()
  1897. diffMonth := sMonth - eMonth
  1898. if diffMonth == 0 {
  1899. //TODO::查询一个月
  1900. months = append(months, sMonth)
  1901. } else {
  1902. for i := sMonth; i <= eMonth; i++ {
  1903. months = append(months, i)
  1904. }
  1905. }
  1906. }
  1907. if len(months) > 0 {
  1908. sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
  1909. }
  1910. //if req.EndDate != "" {
  1911. // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
  1912. //}
  1913. if len(req.MealKindList) > 0 {
  1914. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  1915. }
  1916. if req.EnterPriseKind != 0 {
  1917. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1918. }
  1919. _, err := sess.
  1920. 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").
  1921. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1922. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1923. FindAndCount(&m)
  1924. if err != nil {
  1925. logx.Error(err)
  1926. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1927. return
  1928. }
  1929. var ordNoArr, mealKindListArr []string
  1930. for _, v := range m {
  1931. ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
  1932. }
  1933. 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`"
  1934. for _, v := range req.MealKindList {
  1935. mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
  1936. }
  1937. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1938. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1939. nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
  1940. nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
  1941. var nativeResultsMap = map[string]map[int]int64{}
  1942. for _, v := range nativeResults {
  1943. if nativeResultsMap[v["ord_no"]] == nil {
  1944. nativeResultsMap[v["ord_no"]] = make(map[int]int64)
  1945. }
  1946. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"])
  1947. }
  1948. var list = map[string]map[string]int64{}
  1949. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  1950. centralKitchenForSchoolUserWithDayDb.Set(0)
  1951. for _, v := range m {
  1952. if list[v.Enterprise.Name] == nil {
  1953. list[v.Enterprise.Name] = map[string]int64{}
  1954. }
  1955. var count int64
  1956. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  1957. count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
  1958. list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
  1959. }
  1960. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  1961. count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
  1962. list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
  1963. }
  1964. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  1965. count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
  1966. list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
  1967. }
  1968. list[v.Enterprise.Name]["count"] += count
  1969. }
  1970. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 预定数量统计表"}
  1971. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1972. titleList = []string{"学校名称", "预定总数",
  1973. enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String(),
  1974. enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String(),
  1975. enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String(),
  1976. }
  1977. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1978. xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
  1979. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1980. if err != nil {
  1981. logx.Error(err)
  1982. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1983. panic(err)
  1984. }
  1985. xlsx.SetCellStyle("Sheet1", "A1", "E1", style)
  1986. xlsx.SetColWidth("Sheet1", "A", "A", 30)
  1987. xlsx.SetColWidth("Sheet1", "B", "E", 15)
  1988. j := 3 //表头前两行用了,只能从第三行开始
  1989. total := int64(0)
  1990. total1 := int64(0)
  1991. total2 := int64(0)
  1992. total3 := int64(0)
  1993. for k, v := range list {
  1994. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{k, v["count"],
  1995. v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()],
  1996. v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()],
  1997. v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()]})
  1998. total += v["count"]
  1999. total1 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()]
  2000. total2 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()]
  2001. total3 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()]
  2002. j++
  2003. }
  2004. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
  2005. "合计", total, total1, total2, total3})
  2006. //将文件保存至服务器
  2007. xlsx.SaveAs("./static" + downloadPath)
  2008. break
  2009. case 10:
  2010. //就餐数据统计表
  2011. sTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  2012. eTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  2013. xls, _ := excelize.OpenFile("./static/template/央厨学校(就餐数据统计表).xlsx")
  2014. fileName = "【" + sTime.Format("2006-01-02") + "~" + eTime.Format("2006-01-02") + "】就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  2015. downloadPath = "/export/central_kitchen_for_school/" + fileName
  2016. var list = map[string]map[string]map[string]float64{}
  2017. var dates []string
  2018. if req.StartDate != "" {
  2019. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  2020. centralKitchenForSchoolUserWithDayDb.Set(0)
  2021. diffDays := int(eTime.Sub(sTime).Hours() / 24)
  2022. for i := 0; i <= diffDays; i++ {
  2023. date := sTime.AddDate(0, 0, i)
  2024. dateName := date.Format("2006-01-02")
  2025. dates = append(dates, dateName)
  2026. for _, vv := range req.MealKindList {
  2027. tmpSum, err := centralKitchenForSchoolUserWithDayDb.SumCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling)
  2028. if err != nil {
  2029. logx.Error(err)
  2030. println("<<<<CentralKitchenForSchoolDataStatisticsExport9>>>>>Error:::", err.Error())
  2031. panic(err)
  2032. }
  2033. tmpCount, err := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling)
  2034. if err != nil {
  2035. logx.Error(err)
  2036. println("<<<<CentralKitchenForSchoolDataStatisticsExport9>>>>>Error:::", err.Error())
  2037. panic(err)
  2038. }
  2039. if list[dateName] == nil {
  2040. list[dateName] = map[string]map[string]float64{}
  2041. }
  2042. if list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] == nil {
  2043. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] = map[string]float64{}
  2044. }
  2045. if list[dateName]["合计"] == nil {
  2046. list[dateName]["合计"] = make(map[string]float64)
  2047. }
  2048. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["sum"] = tmpSum
  2049. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["count"] = float64(tmpCount)
  2050. list[dateName]["合计"]["sum"] += tmpSum
  2051. list[dateName]["合计"]["count"] += float64(tmpCount)
  2052. }
  2053. }
  2054. }
  2055. //xls.SetSheetRow("", "A1", &titleList)
  2056. //sheetIndex := 2 //第一个表是模板表
  2057. //xls.NewSheet("sheet1") //1、新建表格
  2058. //xls.CopySheet(1, sheetIndex)
  2059. j := 4 //表头前三"早餐"行被占用了,只能从第四行开始
  2060. var totalMap = map[string]float64{}
  2061. for _, date := range dates {
  2062. for kk, v := range list {
  2063. if date == kk {
  2064. xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{kk,
  2065. v["早餐"]["count"], v["早餐"]["sum"],
  2066. v["午餐"]["count"], v["午餐"]["sum"],
  2067. v["晚餐"]["count"], v["晚餐"]["sum"],
  2068. v["合计"]["count"], v["合计"]["sum"],
  2069. })
  2070. totalMap["breakfast_count"] += v["早餐"]["count"]
  2071. totalMap["breakfast_sum"] += v["早餐"]["sum"]
  2072. totalMap["lunch_count"] += v["午餐"]["count"]
  2073. totalMap["lunch_sum"] += v["午餐"]["sum"]
  2074. totalMap["dinner_count"] += v["晚餐"]["count"]
  2075. totalMap["dinner_sum"] += v["晚餐"]["sum"]
  2076. totalMap["total_count"] += v["合计"]["count"]
  2077. totalMap["total_sum"] += v["合计"]["sum"]
  2078. j++
  2079. }
  2080. }
  2081. }
  2082. //xls.DeleteSheet("template") //删除模板表
  2083. xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{"总计",
  2084. totalMap["breakfast_count"], totalMap["breakfast_sum"],
  2085. totalMap["lunch_count"], totalMap["lunch_sum"],
  2086. totalMap["dinner_count"], totalMap["dinner_sum"],
  2087. totalMap["total_count"], totalMap["total_sum"],
  2088. })
  2089. //将文件保存至服务器
  2090. xls.SaveAs("./static" + downloadPath)
  2091. break
  2092. }
  2093. //新增数据
  2094. centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{}
  2095. centralKitchenForSchoolExportRecordsDb.Set()
  2096. marshal, _ := json.Marshal(req)
  2097. centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{
  2098. Name: fileName,
  2099. DownloadPath: downloadPath,
  2100. Kind: kind,
  2101. ReqContent: string(marshal),
  2102. CreateAt: now.Format("2006-01-02 15:04:05"),
  2103. UpdateAt: now.Format("2006-01-02 15:04:05"),
  2104. })
  2105. }
  2106. }
  2107. func CentralKitchenForSchoolDataStatisticsContrast(req md.CentralKitchenForSchoolDataStatisticsContrastReq) {
  2108. var titleList []string
  2109. var fileName, downloadPath string
  2110. var now = time.Now()
  2111. xlsx := excelize.NewFile()
  2112. //数据对比
  2113. fileName = "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  2114. downloadPath = "/export/central_kitchen_for_school/" + fileName
  2115. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  2116. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  2117. if req.EnterpriseId != 0 {
  2118. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  2119. }
  2120. if req.Date1[0] != "" {
  2121. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local)
  2122. sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02"))
  2123. }
  2124. if req.Date1[1] != "" {
  2125. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[1], time.Local)
  2126. sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02"))
  2127. }
  2128. if len(req.MealKindList) > 0 {
  2129. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  2130. }
  2131. if req.EnterPriseKind != 0 {
  2132. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  2133. }
  2134. _, err := sess.
  2135. 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").
  2136. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  2137. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  2138. Join("LEFT", "user", "user.id = user_identity.uid").
  2139. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  2140. Join("LEFT", "class", "class_with_user.class_id = class.id").
  2141. Join("LEFT", "grade", "class.grade_id = grade.id").
  2142. FindAndCount(&m)
  2143. if err != nil {
  2144. logx.Error(err)
  2145. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2146. return
  2147. }
  2148. var m1 []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  2149. sess1 := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  2150. if req.EnterpriseId != 0 {
  2151. sess1.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  2152. }
  2153. if req.Date2[0] != "" {
  2154. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local)
  2155. sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02"))
  2156. }
  2157. if req.Date2[1] != "" {
  2158. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[1], time.Local)
  2159. sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02"))
  2160. }
  2161. if len(req.MealKindList) > 0 {
  2162. sess1.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  2163. }
  2164. _, err1 := sess1.
  2165. 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").
  2166. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  2167. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  2168. Join("LEFT", "user", "user.id = user_identity.uid").
  2169. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  2170. Join("LEFT", "class", "class_with_user.class_id = class.id").
  2171. Join("LEFT", "grade", "class.grade_id = grade.id").
  2172. FindAndCount(&m1)
  2173. if err1 != nil {
  2174. logx.Error(err1)
  2175. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2176. return
  2177. }
  2178. var list = map[string]map[string]map[string]map[string]string{}
  2179. for _, v := range m {
  2180. if list[v.Enterprise.Name] == nil {
  2181. list[v.Enterprise.Name] = make(map[string]map[string]map[string]string)
  2182. }
  2183. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  2184. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string)
  2185. }
  2186. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  2187. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string)
  2188. }
  2189. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone
  2190. }
  2191. var list1 = map[string]map[string]map[string]map[string]string{}
  2192. for _, v := range m1 {
  2193. if list1[v.Enterprise.Name] == nil {
  2194. list1[v.Enterprise.Name] = make(map[string]map[string]map[string]string)
  2195. }
  2196. if list1[v.Enterprise.Name][v.Grade.Name] == nil {
  2197. list1[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string)
  2198. }
  2199. if list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  2200. list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string)
  2201. }
  2202. list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone
  2203. }
  2204. var xlsFileName, xlsDownloadPath []string
  2205. for k1, v1 := range list {
  2206. tmpFileName := k1 + "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  2207. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  2208. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local)
  2209. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local)
  2210. //查询当前学校下的班级升序
  2211. tmpEnterpriseDb := db.EnterpriseDb{}
  2212. tmpEnterpriseDb.Set()
  2213. tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
  2214. if err11 != nil {
  2215. logx.Error(err11)
  2216. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err11.Error())
  2217. panic(err11)
  2218. }
  2219. tmpClassDb := db.ClassDb{}
  2220. tmpClassDb.Set(0)
  2221. classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
  2222. if err != nil {
  2223. logx.Error(err)
  2224. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  2225. panic(err)
  2226. }
  2227. for _, class := range *classList {
  2228. for k2, v2 := range v1 {
  2229. if k2 == "" {
  2230. //若年级为空,则为教师
  2231. continue
  2232. }
  2233. for k3, v3 := range v2 {
  2234. if class.Name != k3 {
  2235. continue
  2236. }
  2237. xlsx.NewSheet(k3)
  2238. titleList = []string{startDate.Format("2006-01") + "~~" + endDate.Format("2006-01") + " [" + k1 + ", " + k3 + "] 订餐数据对比"}
  2239. xlsx.SetSheetRow(k3, "A1", &titleList)
  2240. titleList = []string{"姓名", "家长联系电话"}
  2241. xlsx.SetSheetRow(k3, "A2", &titleList)
  2242. xlsx.MergeCell(k3, "A1", "B1") //合并单元格
  2243. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  2244. if err != nil {
  2245. logx.Error(err)
  2246. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  2247. panic(err)
  2248. }
  2249. xlsx.SetCellStyle(k3, "A1", "B1", style)
  2250. xlsx.SetColWidth(k3, "A", "B", 40)
  2251. j := 2 //表头被第一行用了,只能从第二行开始
  2252. for k4, v4 := range v3 {
  2253. //TODO::判断当前用户是否在新的月份里面
  2254. fmt.Println("11111111111111", list1[k1])
  2255. fmt.Println("22222222222222", list1[k1][k2])
  2256. fmt.Println("33333333333333", list1[k1][k2][k3])
  2257. fmt.Println("44444444444444", list1[k1][k2][k3][k4])
  2258. if list1[k1] == nil || list1[k1][k2] == nil || list1[k1][k2][k3] == nil || list1[k1][k2][k3][k4] == "" {
  2259. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  2260. k4, v4})
  2261. j++
  2262. }
  2263. }
  2264. }
  2265. }
  2266. }
  2267. //将文件保存至服务器
  2268. xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  2269. err1 := xlsx.SaveAs(tmpDownloadPath)
  2270. if err1 != nil {
  2271. logx.Error(err1)
  2272. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2273. panic(err1)
  2274. }
  2275. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  2276. xlsFileName = append(xlsFileName, tmpFileName)
  2277. }
  2278. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  2279. if err != nil {
  2280. logx.Error(err)
  2281. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2282. panic(err)
  2283. }
  2284. defer archive.Close()
  2285. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  2286. for k, v := range xlsDownloadPath {
  2287. w, err1 := zipWriter.Create("数据对比/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  2288. if err1 != nil {
  2289. logx.Error(err1)
  2290. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2291. panic(err1)
  2292. }
  2293. f, err1 := os.Open(v) //打开待压缩的文件
  2294. if err1 != nil {
  2295. logx.Error(err1)
  2296. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2297. panic(err1)
  2298. }
  2299. if _, err1 = io.Copy(w, f); err != nil {
  2300. logx.Error(err1)
  2301. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2302. panic(err1)
  2303. }
  2304. if err1 != nil {
  2305. logx.Error(err1)
  2306. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2307. panic(err1)
  2308. }
  2309. f.Close()
  2310. os.RemoveAll(v) //TODO::移除源文件
  2311. }
  2312. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  2313. if err != nil {
  2314. panic(err)
  2315. }
  2316. //新增数据
  2317. centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{}
  2318. centralKitchenForSchoolExportRecordsDb.Set()
  2319. marshal, _ := json.Marshal(req)
  2320. centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{
  2321. Name: fileName,
  2322. DownloadPath: downloadPath,
  2323. Kind: 9, //数据对比
  2324. ReqContent: string(marshal),
  2325. CreateAt: now.Format("2006-01-02 15:04:05"),
  2326. UpdateAt: now.Format("2006-01-02 15:04:05"),
  2327. })
  2328. }
  2329. func JudgeSelfSupportForMealTime(mealDate string) (mealZh string) {
  2330. mealZh = "未知"
  2331. mealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealDate, time.Local)
  2332. for _, v := range md.SelfSupportForMealTimeMapping {
  2333. //判断时间大小
  2334. tmpFromTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["from"]+":00", time.Local)
  2335. tmpToTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["to"]+":00", time.Local)
  2336. fmt.Println(">>>>>>>>>>>>>", mealTime.After(tmpFromTime))
  2337. fmt.Println("<<<<<<<<<<<<<", mealTime.Before(tmpToTime))
  2338. if mealTime.After(tmpFromTime) && mealTime.Before(tmpToTime) {
  2339. mealZh = v["name"]
  2340. }
  2341. }
  2342. return
  2343. }