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

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