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

2490 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. var incomeTotal, refundTotal, realityAmountTotal, rateFeeTotal float64
  1658. j := 3 //表头前两行用了,只能从第三行开始
  1659. for _, v := range m {
  1660. var income, refund string
  1661. //统计收入
  1662. 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)
  1663. mapArr1, err := db.QueryNativeString(db.Db, sql1)
  1664. if err != nil {
  1665. logx.Error(err)
  1666. println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
  1667. return
  1668. }
  1669. if mapArr1 != nil {
  1670. income = mapArr1[0]["total"]
  1671. }
  1672. //统计退款
  1673. //查询出当前学校下所有的学生
  1674. userIdentityDb := db.UserIdentityDb{}
  1675. userIdentityDb.Set(0)
  1676. userIdentities, _ := userIdentityDb.FindUserIdentityForEnterprise(v.Id)
  1677. var userIdentityIds []string
  1678. for _, v := range *userIdentities {
  1679. userIdentityIds = append(userIdentityIds, utils.IntToStr(v.Id))
  1680. }
  1681. if len(userIdentityIds) != 0 {
  1682. userIdentityStr := php2go.Implode(",", userIdentityIds)
  1683. 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'",
  1684. enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete, userIdentityStr, req.StartDate, req.EndDate)
  1685. mapArr2, err := db.QueryNativeString(db.Db, sql2)
  1686. if err != nil {
  1687. logx.Error(err)
  1688. println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
  1689. return
  1690. }
  1691. if mapArr2 != nil {
  1692. refund = mapArr2[0]["total"]
  1693. }
  1694. }
  1695. realityAmount := utils.StrToFloat64(income) - utils.StrToFloat64(refund)
  1696. rateFee := realityAmount * 0.0038
  1697. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.Name, income, refund, realityAmount, rateFee})
  1698. incomeTotal += utils.StrToFloat64(income)
  1699. refundTotal += utils.StrToFloat64(refund)
  1700. realityAmountTotal += realityAmount
  1701. rateFeeTotal += rateFee
  1702. j++
  1703. }
  1704. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{"总计", incomeTotal, refundTotal, realityAmountTotal, rateFeeTotal})
  1705. //将文件保存至服务器
  1706. xlsx.SaveAs("./static" + downloadPath)
  1707. break
  1708. case 7:
  1709. xlsx := excelize.NewFile()
  1710. //班级收款明细表
  1711. fileName = "班级收款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  1712. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1713. //查找订单数据
  1714. sess := db.Db.Desc("central_kitchen_for_school_package_ord.id")
  1715. sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess).And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent)
  1716. if req.EnterpriseId != 0 {
  1717. sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId)
  1718. }
  1719. if req.StartDate != "" {
  1720. sess.And("central_kitchen_for_school_package_ord.create_at >= ?", req.StartDate)
  1721. }
  1722. if req.EndDate != "" {
  1723. sess.And("central_kitchen_for_school_package_ord.create_at <= ?", req.EndDate)
  1724. }
  1725. if req.EnterPriseKind != 0 {
  1726. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1727. }
  1728. var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity
  1729. _, err := sess.
  1730. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1731. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1732. Join("LEFT", "user", "user.id = user_identity.uid").
  1733. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  1734. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1735. Join("LEFT", "grade", "class.grade_id = grade.id").
  1736. FindAndCount(&m)
  1737. if err != nil {
  1738. logx.Error(err)
  1739. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1740. return
  1741. }
  1742. 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")
  1743. if req.EnterpriseId != 0 {
  1744. sess1.And("enterprise.id =?", req.EnterpriseId)
  1745. }
  1746. if req.StartDate != "" {
  1747. sess1.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
  1748. }
  1749. if req.EndDate != "" {
  1750. sess1.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
  1751. }
  1752. var mm []*db.CentralKitchenForSchoolUserRefundDayWithData
  1753. _, err = sess1.
  1754. 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").
  1755. 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").
  1756. Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
  1757. Join("LEFT", "user", "user_identity.uid = user.id").
  1758. Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
  1759. Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
  1760. Join("LEFT", "class", "class_with_user.class_id = class.id").
  1761. Join("LEFT", "grade", "class.grade_id = grade.id").
  1762. Desc("central_kitchen_for_school_user_refund_day.id").
  1763. FindAndCount(&mm)
  1764. if err != nil {
  1765. logx.Error(err)
  1766. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1767. return
  1768. }
  1769. var list = map[string]map[string]map[string]map[string]float64{}
  1770. for _, v := range m {
  1771. if list[v.Enterprise.Name] == nil {
  1772. list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  1773. }
  1774. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1775. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64)
  1776. }
  1777. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1778. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64)
  1779. }
  1780. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["income"] += utils.StrToFloat64(v.CentralKitchenForSchoolPackageOrd.TotalPrice)
  1781. }
  1782. for _, v := range mm {
  1783. if list[v.Enterprise.Name] == nil {
  1784. list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64)
  1785. }
  1786. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  1787. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64)
  1788. }
  1789. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  1790. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64)
  1791. }
  1792. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["refund"] += utils.StrToFloat64(v.CentralKitchenForSchoolUserRefundDay.Amount)
  1793. }
  1794. var xlsFileName, xlsDownloadPath []string
  1795. for k1, v1 := range list {
  1796. tmpFileName := k1 + "班级收款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1797. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  1798. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1799. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1800. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") 班级收款明细"}
  1801. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1802. titleList = []string{"年级", "班级", "预定总费用", "退款总计"}
  1803. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1804. xlsx.MergeCell("Sheet1", "A1", "D1") //合并单元格
  1805. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1806. if err != nil {
  1807. logx.Error(err)
  1808. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1809. panic(err)
  1810. }
  1811. xlsx.SetCellStyle("Sheet1", "A1", "D1", style)
  1812. xlsx.SetColWidth("Sheet1", "A", "D", 20)
  1813. j := 3 //表头前两行用了,只能从第三行开始
  1814. var sumClassNum = int64(0)
  1815. var sumIncome, sumRefund = float64(0), float64(0)
  1816. for k2, v2 := range v1 {
  1817. if k2 == "" {
  1818. //若年级为空,则为教师餐
  1819. continue
  1820. }
  1821. for k3, v3 := range v2 {
  1822. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{k2, k3, utils.Float64ToStr(v3["income"]), utils.Float64ToStr(v3["refund"])})
  1823. sumClassNum++
  1824. sumIncome += v3["income"]
  1825. sumRefund += v3["refund"]
  1826. j++
  1827. }
  1828. }
  1829. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
  1830. "合计", sumClassNum, sumIncome, sumRefund})
  1831. //将文件保存至服务器
  1832. err1 := xlsx.SaveAs(tmpDownloadPath)
  1833. if err1 != nil {
  1834. logx.Error(err1)
  1835. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1836. panic(err1)
  1837. }
  1838. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  1839. xlsFileName = append(xlsFileName, tmpFileName)
  1840. }
  1841. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  1842. if err != nil {
  1843. logx.Error(err)
  1844. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
  1845. panic(err)
  1846. }
  1847. defer archive.Close()
  1848. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  1849. for k, v := range xlsDownloadPath {
  1850. w, err1 := zipWriter.Create("班级收款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  1851. if err1 != nil {
  1852. logx.Error(err1)
  1853. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1854. panic(err1)
  1855. }
  1856. f, err1 := os.Open(v) //打开待压缩的文件
  1857. if err1 != nil {
  1858. logx.Error(err1)
  1859. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1860. panic(err1)
  1861. }
  1862. if _, err1 = io.Copy(w, f); err != nil {
  1863. logx.Error(err1)
  1864. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1865. panic(err1)
  1866. }
  1867. if err1 != nil {
  1868. logx.Error(err1)
  1869. println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
  1870. panic(err1)
  1871. }
  1872. f.Close()
  1873. os.RemoveAll(v) //TODO::移除源文件
  1874. }
  1875. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  1876. if err != nil {
  1877. panic(err)
  1878. }
  1879. break
  1880. case 8:
  1881. xlsx := excelize.NewFile()
  1882. //学校预定数量统计表
  1883. fileName = "学校预定数量统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  1884. downloadPath = "/export/central_kitchen_for_school/" + fileName
  1885. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1886. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1887. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  1888. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  1889. if req.EnterpriseId != 0 {
  1890. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  1891. }
  1892. var months []time.Month
  1893. if req.StartDate != "" {
  1894. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1895. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1896. _, sMonth, _ := sDate.Date()
  1897. _, eMonth, _ := eDate.Date()
  1898. diffMonth := sMonth - eMonth
  1899. if diffMonth == 0 {
  1900. //TODO::查询一个月
  1901. months = append(months, sMonth)
  1902. } else {
  1903. for i := sMonth; i <= eMonth; i++ {
  1904. months = append(months, i)
  1905. }
  1906. }
  1907. }
  1908. if len(months) > 0 {
  1909. sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
  1910. }
  1911. //if req.EndDate != "" {
  1912. // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
  1913. //}
  1914. if len(req.MealKindList) > 0 {
  1915. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  1916. }
  1917. if req.EnterPriseKind != 0 {
  1918. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  1919. }
  1920. _, err := sess.
  1921. 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").
  1922. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  1923. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  1924. FindAndCount(&m)
  1925. if err != nil {
  1926. logx.Error(err)
  1927. println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1928. return
  1929. }
  1930. var ordNoArr, mealKindListArr []string
  1931. for _, v := range m {
  1932. ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
  1933. }
  1934. 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`"
  1935. for _, v := range req.MealKindList {
  1936. mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
  1937. }
  1938. sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  1939. eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  1940. nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
  1941. nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
  1942. var nativeResultsMap = map[string]map[int]int64{}
  1943. for _, v := range nativeResults {
  1944. if nativeResultsMap[v["ord_no"]] == nil {
  1945. nativeResultsMap[v["ord_no"]] = make(map[int]int64)
  1946. }
  1947. nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"])
  1948. }
  1949. var list = map[string]map[string]int64{}
  1950. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  1951. centralKitchenForSchoolUserWithDayDb.Set(0)
  1952. for _, v := range m {
  1953. if list[v.Enterprise.Name] == nil {
  1954. list[v.Enterprise.Name] = map[string]int64{}
  1955. }
  1956. var count int64
  1957. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
  1958. count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
  1959. list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
  1960. }
  1961. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
  1962. count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
  1963. list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
  1964. }
  1965. if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
  1966. count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
  1967. list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
  1968. }
  1969. list[v.Enterprise.Name]["count"] += count
  1970. }
  1971. titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 预定数量统计表"}
  1972. xlsx.SetSheetRow("Sheet1", "A1", &titleList)
  1973. titleList = []string{"学校名称", "预定总数",
  1974. enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String(),
  1975. enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String(),
  1976. enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String(),
  1977. }
  1978. xlsx.SetSheetRow("Sheet1", "A2", &titleList)
  1979. xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
  1980. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  1981. if err != nil {
  1982. logx.Error(err)
  1983. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  1984. panic(err)
  1985. }
  1986. xlsx.SetCellStyle("Sheet1", "A1", "E1", style)
  1987. xlsx.SetColWidth("Sheet1", "A", "A", 30)
  1988. xlsx.SetColWidth("Sheet1", "B", "E", 15)
  1989. j := 3 //表头前两行用了,只能从第三行开始
  1990. total := int64(0)
  1991. total1 := int64(0)
  1992. total2 := int64(0)
  1993. total3 := int64(0)
  1994. for k, v := range list {
  1995. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{k, v["count"],
  1996. v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()],
  1997. v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()],
  1998. v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()]})
  1999. total += v["count"]
  2000. total1 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()]
  2001. total2 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()]
  2002. total3 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()]
  2003. j++
  2004. }
  2005. xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
  2006. "合计", total, total1, total2, total3})
  2007. //将文件保存至服务器
  2008. xlsx.SaveAs("./static" + downloadPath)
  2009. break
  2010. case 10:
  2011. //就餐数据统计表
  2012. sTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
  2013. eTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
  2014. xls, _ := excelize.OpenFile("./static/template/央厨学校(就餐数据统计表).xlsx")
  2015. fileName = "【" + sTime.Format("2006-01-02") + "~" + eTime.Format("2006-01-02") + "】就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  2016. downloadPath = "/export/central_kitchen_for_school/" + fileName
  2017. var list = map[string]map[string]map[string]float64{}
  2018. var dates []string
  2019. if req.StartDate != "" {
  2020. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  2021. centralKitchenForSchoolUserWithDayDb.Set(0)
  2022. diffDays := int(eTime.Sub(sTime).Hours() / 24)
  2023. for i := 0; i <= diffDays; i++ {
  2024. date := sTime.AddDate(0, 0, i)
  2025. dateName := date.Format("2006-01-02")
  2026. dates = append(dates, dateName)
  2027. for _, vv := range req.MealKindList {
  2028. tmpSum, err := centralKitchenForSchoolUserWithDayDb.SumCentralKitchenForSchoolUserWithDayByKind(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. tmpCount, err := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling)
  2035. if err != nil {
  2036. logx.Error(err)
  2037. println("<<<<CentralKitchenForSchoolDataStatisticsExport9>>>>>Error:::", err.Error())
  2038. panic(err)
  2039. }
  2040. if list[dateName] == nil {
  2041. list[dateName] = map[string]map[string]float64{}
  2042. }
  2043. if list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] == nil {
  2044. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] = map[string]float64{}
  2045. }
  2046. if list[dateName]["合计"] == nil {
  2047. list[dateName]["合计"] = make(map[string]float64)
  2048. }
  2049. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["sum"] = tmpSum
  2050. list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["count"] = float64(tmpCount)
  2051. list[dateName]["合计"]["sum"] += tmpSum
  2052. list[dateName]["合计"]["count"] += float64(tmpCount)
  2053. }
  2054. }
  2055. }
  2056. //xls.SetSheetRow("", "A1", &titleList)
  2057. //sheetIndex := 2 //第一个表是模板表
  2058. //xls.NewSheet("sheet1") //1、新建表格
  2059. //xls.CopySheet(1, sheetIndex)
  2060. j := 4 //表头前三"早餐"行被占用了,只能从第四行开始
  2061. var totalMap = map[string]float64{}
  2062. for _, date := range dates {
  2063. for kk, v := range list {
  2064. if date == kk {
  2065. xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{kk,
  2066. v["早餐"]["count"], v["早餐"]["sum"],
  2067. v["午餐"]["count"], v["午餐"]["sum"],
  2068. v["晚餐"]["count"], v["晚餐"]["sum"],
  2069. v["合计"]["count"], v["合计"]["sum"],
  2070. })
  2071. totalMap["breakfast_count"] += v["早餐"]["count"]
  2072. totalMap["breakfast_sum"] += v["早餐"]["sum"]
  2073. totalMap["lunch_count"] += v["午餐"]["count"]
  2074. totalMap["lunch_sum"] += v["午餐"]["sum"]
  2075. totalMap["dinner_count"] += v["晚餐"]["count"]
  2076. totalMap["dinner_sum"] += v["晚餐"]["sum"]
  2077. totalMap["total_count"] += v["合计"]["count"]
  2078. totalMap["total_sum"] += v["合计"]["sum"]
  2079. j++
  2080. }
  2081. }
  2082. }
  2083. //xls.DeleteSheet("template") //删除模板表
  2084. xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{"总计",
  2085. totalMap["breakfast_count"], totalMap["breakfast_sum"],
  2086. totalMap["lunch_count"], totalMap["lunch_sum"],
  2087. totalMap["dinner_count"], totalMap["dinner_sum"],
  2088. totalMap["total_count"], totalMap["total_sum"],
  2089. })
  2090. //将文件保存至服务器
  2091. xls.SaveAs("./static" + downloadPath)
  2092. break
  2093. }
  2094. //新增数据
  2095. centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{}
  2096. centralKitchenForSchoolExportRecordsDb.Set()
  2097. marshal, _ := json.Marshal(req)
  2098. centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{
  2099. Name: fileName,
  2100. DownloadPath: downloadPath,
  2101. Kind: kind,
  2102. ReqContent: string(marshal),
  2103. CreateAt: now.Format("2006-01-02 15:04:05"),
  2104. UpdateAt: now.Format("2006-01-02 15:04:05"),
  2105. })
  2106. }
  2107. }
  2108. func CentralKitchenForSchoolDataStatisticsContrast(req md.CentralKitchenForSchoolDataStatisticsContrastReq) {
  2109. var titleList []string
  2110. var fileName, downloadPath string
  2111. var now = time.Now()
  2112. xlsx := excelize.NewFile()
  2113. //数据对比
  2114. fileName = "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
  2115. downloadPath = "/export/central_kitchen_for_school/" + fileName
  2116. var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  2117. sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  2118. if req.EnterpriseId != 0 {
  2119. sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  2120. }
  2121. if req.Date1[0] != "" {
  2122. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local)
  2123. sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02"))
  2124. }
  2125. if req.Date1[1] != "" {
  2126. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[1], time.Local)
  2127. sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02"))
  2128. }
  2129. if len(req.MealKindList) > 0 {
  2130. sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  2131. }
  2132. if req.EnterPriseKind != 0 {
  2133. sess.And("enterprise.kind = ?", req.EnterPriseKind)
  2134. }
  2135. _, err := sess.
  2136. 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").
  2137. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  2138. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  2139. Join("LEFT", "user", "user.id = user_identity.uid").
  2140. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  2141. Join("LEFT", "class", "class_with_user.class_id = class.id").
  2142. Join("LEFT", "grade", "class.grade_id = grade.id").
  2143. FindAndCount(&m)
  2144. if err != nil {
  2145. logx.Error(err)
  2146. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2147. return
  2148. }
  2149. var m1 []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
  2150. sess1 := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
  2151. if req.EnterpriseId != 0 {
  2152. sess1.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
  2153. }
  2154. if req.Date2[0] != "" {
  2155. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local)
  2156. sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02"))
  2157. }
  2158. if req.Date2[1] != "" {
  2159. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[1], time.Local)
  2160. sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02"))
  2161. }
  2162. if len(req.MealKindList) > 0 {
  2163. sess1.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
  2164. }
  2165. _, err1 := sess1.
  2166. 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").
  2167. Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
  2168. Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
  2169. Join("LEFT", "user", "user.id = user_identity.uid").
  2170. Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
  2171. Join("LEFT", "class", "class_with_user.class_id = class.id").
  2172. Join("LEFT", "grade", "class.grade_id = grade.id").
  2173. FindAndCount(&m1)
  2174. if err1 != nil {
  2175. logx.Error(err1)
  2176. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2177. return
  2178. }
  2179. var list = map[string]map[string]map[string]map[string]string{}
  2180. for _, v := range m {
  2181. if list[v.Enterprise.Name] == nil {
  2182. list[v.Enterprise.Name] = make(map[string]map[string]map[string]string)
  2183. }
  2184. if list[v.Enterprise.Name][v.Grade.Name] == nil {
  2185. list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string)
  2186. }
  2187. if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  2188. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string)
  2189. }
  2190. list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone
  2191. }
  2192. var list1 = map[string]map[string]map[string]map[string]string{}
  2193. for _, v := range m1 {
  2194. if list1[v.Enterprise.Name] == nil {
  2195. list1[v.Enterprise.Name] = make(map[string]map[string]map[string]string)
  2196. }
  2197. if list1[v.Enterprise.Name][v.Grade.Name] == nil {
  2198. list1[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string)
  2199. }
  2200. if list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
  2201. list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string)
  2202. }
  2203. list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone
  2204. }
  2205. var xlsFileName, xlsDownloadPath []string
  2206. for k1, v1 := range list {
  2207. tmpFileName := k1 + "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
  2208. tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
  2209. startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local)
  2210. endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local)
  2211. //查询当前学校下的班级升序
  2212. tmpEnterpriseDb := db.EnterpriseDb{}
  2213. tmpEnterpriseDb.Set()
  2214. tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
  2215. if err11 != nil {
  2216. logx.Error(err11)
  2217. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err11.Error())
  2218. panic(err11)
  2219. }
  2220. tmpClassDb := db.ClassDb{}
  2221. tmpClassDb.Set(0)
  2222. classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
  2223. if err != nil {
  2224. logx.Error(err)
  2225. println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
  2226. panic(err)
  2227. }
  2228. for _, class := range *classList {
  2229. for k2, v2 := range v1 {
  2230. if k2 == "" {
  2231. //若年级为空,则为教师
  2232. continue
  2233. }
  2234. for k3, v3 := range v2 {
  2235. if class.Name != k3 {
  2236. continue
  2237. }
  2238. xlsx.NewSheet(k3)
  2239. titleList = []string{startDate.Format("2006-01") + "~~" + endDate.Format("2006-01") + " [" + k1 + ", " + k3 + "] 订餐数据对比"}
  2240. xlsx.SetSheetRow(k3, "A1", &titleList)
  2241. titleList = []string{"姓名", "家长联系电话"}
  2242. xlsx.SetSheetRow(k3, "A2", &titleList)
  2243. xlsx.MergeCell(k3, "A1", "B1") //合并单元格
  2244. style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
  2245. if err != nil {
  2246. logx.Error(err)
  2247. println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
  2248. panic(err)
  2249. }
  2250. xlsx.SetCellStyle(k3, "A1", "B1", style)
  2251. xlsx.SetColWidth(k3, "A", "B", 40)
  2252. j := 2 //表头被第一行用了,只能从第二行开始
  2253. for k4, v4 := range v3 {
  2254. //TODO::判断当前用户是否在新的月份里面
  2255. fmt.Println("11111111111111", list1[k1])
  2256. fmt.Println("22222222222222", list1[k1][k2])
  2257. fmt.Println("33333333333333", list1[k1][k2][k3])
  2258. fmt.Println("44444444444444", list1[k1][k2][k3][k4])
  2259. if list1[k1] == nil || list1[k1][k2] == nil || list1[k1][k2][k3] == nil || list1[k1][k2][k3][k4] == "" {
  2260. xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
  2261. k4, v4})
  2262. j++
  2263. }
  2264. }
  2265. }
  2266. }
  2267. }
  2268. //将文件保存至服务器
  2269. xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
  2270. err1 := xlsx.SaveAs(tmpDownloadPath)
  2271. if err1 != nil {
  2272. logx.Error(err1)
  2273. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2274. panic(err1)
  2275. }
  2276. xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
  2277. xlsFileName = append(xlsFileName, tmpFileName)
  2278. }
  2279. archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
  2280. if err != nil {
  2281. logx.Error(err)
  2282. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
  2283. panic(err)
  2284. }
  2285. defer archive.Close()
  2286. zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
  2287. for k, v := range xlsDownloadPath {
  2288. w, err1 := zipWriter.Create("数据对比/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
  2289. if err1 != nil {
  2290. logx.Error(err1)
  2291. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2292. panic(err1)
  2293. }
  2294. f, err1 := os.Open(v) //打开待压缩的文件
  2295. if err1 != nil {
  2296. logx.Error(err1)
  2297. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2298. panic(err1)
  2299. }
  2300. if _, err1 = io.Copy(w, f); err != nil {
  2301. logx.Error(err1)
  2302. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2303. panic(err1)
  2304. }
  2305. if err1 != nil {
  2306. logx.Error(err1)
  2307. println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
  2308. panic(err1)
  2309. }
  2310. f.Close()
  2311. os.RemoveAll(v) //TODO::移除源文件
  2312. }
  2313. zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
  2314. if err != nil {
  2315. panic(err)
  2316. }
  2317. //新增数据
  2318. centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{}
  2319. centralKitchenForSchoolExportRecordsDb.Set()
  2320. marshal, _ := json.Marshal(req)
  2321. centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{
  2322. Name: fileName,
  2323. DownloadPath: downloadPath,
  2324. Kind: 9, //数据对比
  2325. ReqContent: string(marshal),
  2326. CreateAt: now.Format("2006-01-02 15:04:05"),
  2327. UpdateAt: now.Format("2006-01-02 15:04:05"),
  2328. })
  2329. }
  2330. func JudgeSelfSupportForMealTime(mealDate string) (mealZh string) {
  2331. mealZh = "未知"
  2332. mealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealDate, time.Local)
  2333. for _, v := range md.SelfSupportForMealTimeMapping {
  2334. //判断时间大小
  2335. tmpFromTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["from"]+":00", time.Local)
  2336. tmpToTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["to"]+":00", time.Local)
  2337. fmt.Println(">>>>>>>>>>>>>", mealTime.After(tmpFromTime))
  2338. fmt.Println("<<<<<<<<<<<<<", mealTime.Before(tmpToTime))
  2339. if mealTime.After(tmpFromTime) && mealTime.Before(tmpToTime) {
  2340. mealZh = v["name"]
  2341. }
  2342. }
  2343. return
  2344. }