|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539 |
- package svc
-
- import (
- "applet/app/admin/md"
- "applet/app/db"
- "applet/app/db/model"
- "applet/app/enum"
- "applet/app/utils"
- "applet/app/utils/logx"
- "archive/zip"
- "encoding/json"
- "fmt"
- "github.com/360EntSecGroup-Skylar/excelize"
- "github.com/syyongx/php2go"
- "io"
- "os"
- "strconv"
- "strings"
- "time"
- )
-
- func NursingHomeDataStatisticsExport(req md.NursingHomeDataStatisticsExportReq) {
- var titleList []string
- var fileName string
- var now = time.Now()
- xlsx := excelize.NewFile()
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- switch req.Kind {
- case 1:
- //订单列表
- fileName = "/export/nursing_home/订单列表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
-
- //查找订单数据
- sess := db.Db.Desc("nursing_home_package_ord.id")
- if req.EnterpriseId != 0 {
- sess.And("nursing_home_package_ord.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("nursing_home_package_ord.create_at >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("nursing_home_package_ord.create_at <= ?", req.EndDate)
- }
- var m []*db.NursingHomePackageOrdWithUserIdentity
- _, err := sess.
- Join("LEFT", "user_identity", "nursing_home_package_ord.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = nursing_home_package_ord.enterprise_id").
- Join("LEFT", "user", "user.id = nursing_home_package_ord.uid").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<NursingHomeDataStatisticsExport1>>>>>Error:::", err.Error())
- return
- }
- titleList = []string{"单位名称", "用户身份名称", "用户手机号", "购买类型", "总价", "商户订单号", "支付状态", "购买时间"}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- j := 2 //表头被第一行用了,只能从第二行开始
- for _, v := range m {
- var kind string //1:按年购买 2:按月购买 3:按天购买 4:补餐
- switch v.NursingHomePackageOrd.Kind {
- case 1:
- kind = "按年购买"
- break
- case 2:
- kind = "按月购买"
- break
- case 3:
- kind = "按天购买"
- break
- case 4:
- kind = "补餐"
- break
- }
-
- var state string //0:待支付 1:支付成功 2:支付失败
- switch v.NursingHomePackageOrd.State {
- case enum.NursingHomePackageOrdStateForWait:
- state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForWait)
- break
- case enum.NursingHomePackageOrdStateForSuccess:
- state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForWait)
- break
- case enum.NursingHomePackageOrdStateForFail:
- state = enum.NursingHomePackageOrdState.String(enum.NursingHomePackageOrdStateForFail)
- break
- }
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.Enterprise.Name, v.NursingHomePackageOrd.UserIdentityName, v.User.Phone, kind, v.NursingHomePackageOrd.TotalPrice,
- v.NursingHomePackageOrd.OutTradeNo, state, v.NursingHomePackageOrd.CreateAt})
- j++
- }
- break
- case 2:
- //退款申请表
- fileName = "/export/nursing_home/退款申请表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- var m []*db.NursingHomeUserRefundDayWithData
- sess := db.Db.Desc("nursing_home_user_refund_day.id")
- if req.EnterpriseId != 0 {
- sess.And("enterprise.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("nursing_home_user_refund_day.create_at >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("nursing_home_user_refund_day.create_at <= ?", req.EndDate)
- }
- _, err := sess.
- Join("LEFT", "nursing_home_user_with_day", "nursing_home_user_refund_day.records_id = nursing_home_user_with_day.id").
- Join("LEFT", "nursing_home_package_ord", "nursing_home_user_refund_day.out_trade_no = nursing_home_package_ord.out_trade_no").
- Join("LEFT", "user_identity", "nursing_home_user_with_day.identity_id = user_identity.id").
- Join("LEFT", "user", "user_identity.uid = user.id").
- Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
- Desc("nursing_home_user_refund_day.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<NursingHomeDataStatisticsExport2>>>>>Error:::", err.Error())
- return
- }
-
- titleList = []string{"退款单号", "所属订单号", "单位名称", "用户身份名称", "用户手机号", "就餐类型", "就餐时间", "金额", "状态", "退款时间"}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- j := 2 //表头被第一行用了,只能从第二行开始
- for _, v := range m {
- var kind string //就餐类型(1:早餐 2:午餐 3:晚餐)
- switch v.NursingHomeUserWithDay.Kind {
- case enum.NursingHomeUserWithDayKindForBreakfast:
- kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast)
- break
- case enum.NursingHomeUserWithDayKindForLunch:
- kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch)
- break
- case enum.NursingHomeUserWithDayKindForDinner:
- kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner)
- break
- }
-
- var state string //状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成)
- switch v.NursingHomeUserRefundDay.State {
- case enum.NursingHomeUserRefundDayStateForAuditing:
- state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditing)
- break
- case enum.NursingHomeUserRefundDayStateForAuditPass:
- state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditPass)
- break
- case enum.NursingHomeUserRefundDayStateForAuditReject:
- state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditReject)
- break
- case enum.NursingHomeUserRefundDayStateForAuditComplete:
- state = enum.NursingHomeUserRefundDayState.String(enum.NursingHomeUserRefundDayStateForAuditComplete)
- break
- }
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.NursingHomeUserRefundDay.OutRequestNo, v.NursingHomeUserRefundDay.OutTradeNo, v.Enterprise.Name,
- v.NursingHomePackageOrd.UserIdentityName, v.User.Phone, kind, v.NursingHomeUserWithDay.Date, v.NursingHomeUserRefundDay.Amount, state, v.NursingHomeUserRefundDay.RefundDate})
- j++
- }
- xlsx.SaveAs("./static" + fileName + ".xlsx")
- break
- case 3:
- //预定统计表
- fileName = "/export/nursing_home/预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- var m []*db.NursingHomePackageOrdForReserveWithUserIdentity
- sess := db.Db.Desc("nursing_home_package_ord_for_reserve.id")
- if req.EnterpriseId != 0 {
- sess.And("enterprise.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("nursing_home_package_ord_for_reserve.meal_time_start >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("nursing_home_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
- }
- _, err := sess.
- Join("LEFT", "nursing_home_package_ord", "nursing_home_package_ord_for_reserve.out_trade_no = nursing_home_package_ord.out_trade_no").
- Join("LEFT", "user_identity", "nursing_home_package_ord.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<NursingHomeDataStatisticsExport2>>>>>Error:::", err.Error())
- return
- }
-
- titleList = []string{"所属订单号", "单位名称", "用户身份名称", "用户手机号", "预定类型", "预定月份", "就餐时间-开始", "就餐时间-截止"}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- j := 2 //表头被第一行用了,只能从第二行开始
- for _, v := range m {
- var kind string //预定类型(1:早餐 2:午餐 3:晚餐)
- switch v.NursingHomePackageOrdForReserve.Kind {
- case enum.NursingHomeUserWithDayKindForBreakfast:
- kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForBreakfast)
- break
- case enum.NursingHomeUserWithDayKindForLunch:
- kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForLunch)
- break
- case enum.NursingHomeUserWithDayKindForDinner:
- kind = enum.NursingHomeUserWithDayKind.String(enum.NursingHomeUserWithDayKindForDinner)
- break
- }
-
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.NursingHomePackageOrdForReserve.OutTradeNo, v.Enterprise.Name, v.NursingHomePackageOrd.UserIdentityName,
- v.User.Phone, kind, v.NursingHomePackageOrdForReserve.ReserveMonth, v.NursingHomePackageOrdForReserve.MealTimeStart, v.NursingHomePackageOrdForReserve.MealTimeEnd})
- j++
- }
- xlsx.SaveAs("./static" + fileName + ".xlsx")
- break
- }
- //新增数据
- nursingHomeExportRecordsDb := db.NursingHomeExportRecordsDb{}
- nursingHomeExportRecordsDb.Set()
- marshal, _ := json.Marshal(req)
- nursingHomeExportRecordsDb.NursingHomeExportRecordsInsert(&model.NursingHomeExportRecords{
- Name: fileName,
- DownloadPath: fileName,
- Kind: req.Kind,
- ReqContent: string(marshal),
- CreateAt: now.Format("2006-01-02 15:04:05"),
- UpdateAt: now.Format("2006-01-02 15:04:05"),
- })
- }
-
- func SelfSupportForSchoolDataStatisticsExport(req md.SelfSupportForSchoolDataStatisticsExportReq) {
- var titleList []string
- var fileName, downloadPath string
- var now = time.Now()
- switch req.Kind {
- case 1:
- //教师消费统计表
- xlsx, _ := excelize.OpenFile("./static/template/自营学校(教师消费统计表).xlsx")
- fileName = "教师消费统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- downloadPath = "/export/self_support_for_school/" + fileName
-
- //查询数据
- var m []*db.SelfSupportForSchoolOrdWithUserIdentity
- sess := db.Db.Desc("self_support_for_school_ord.id")
- if req.EnterpriseId != 0 {
- sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
-
- sess.And("user_identity.identity = ?", enum.UserIdentityForSelfSupportForTeacher) //只查询老师
- _, err := sess.
- Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").
- Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
- return
- }
-
- //整合数据
- var data = map[string]map[string]map[string]map[string]interface{}{}
- for _, vv := range m {
- if data[vv.Enterprise.Name] == nil {
- data[vv.Enterprise.Name] = make(map[string]map[string]map[string]interface{})
- }
- if data[vv.Enterprise.Name][vv.UserIdentity.Name] == nil {
- data[vv.Enterprise.Name][vv.UserIdentity.Name] = make(map[string]map[string]interface{})
- }
- mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime)
- if data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh] == nil {
- data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh] = make(map[string]interface{})
- }
- data[vv.Enterprise.Name][vv.UserIdentity.Name]["编号"] = map[string]interface{}{
- "id": vv.UserIdentity.IdNo,
- }
- if data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"] == nil {
- data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"] = make(map[string]interface{})
- }
- data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["num"] = utils.AnyToInt64(data[vv.Enterprise.Name][vv.UserIdentity.Name][mealZh]["num"]) + 1
- 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)
- data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["num"] = utils.AnyToInt64(data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["num"]) + 1
- data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["amount"] = utils.AnyToFloat64(data[vv.Enterprise.Name][vv.UserIdentity.Name]["合计"]["amount"]) + utils.AnyToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
- }
-
- xlsx.SetSheetRow("", "A1", &titleList)
- sheetIndex := 2 //第一个表是模板表
- j := 3 //表头前两行被占用了,只能从第三行开始
- for k, v := range data {
- xlsx.NewSheet(k) //1、新建表格
- xlsx.CopySheet(1, sheetIndex)
- var userTotal, breakFastTotal, lunchTotal, dinnerTotal, supperTotal, totalTotal int64
- var breakFastAmountTotal, lunchAmountTotal, dinnerAmountTotal, supperAmountTotal, totalAmountTotal float64
- for kk, vv := range v {
- xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{vv["编号"]["id"], kk,
- vv["早餐"]["num"], vv["早餐"]["amount"],
- vv["午餐"]["num"], vv["午餐"]["amount"],
- vv["晚餐"]["num"], vv["晚餐"]["amount"],
- vv["夜宵"]["num"], vv["夜宵"]["amount"],
- vv["合计"]["num"], vv["合计"]["amount"],
- })
- userTotal++
- if vv["早餐"]["num"] != nil {
- breakFastTotal += vv["早餐"]["num"].(int64)
- }
- if vv["午餐"]["num"] != nil {
- lunchTotal += vv["午餐"]["num"].(int64)
- }
- if vv["晚餐"]["num"] != nil {
- dinnerTotal += vv["晚餐"]["num"].(int64)
- }
- if vv["夜宵"]["num"] != nil {
- supperTotal += vv["夜宵"]["num"].(int64)
- }
- if vv["合计"]["num"] != nil {
- totalTotal += vv["合计"]["num"].(int64)
- }
- if vv["早餐"]["amount"] != nil {
- breakFastAmountTotal += vv["早餐"]["amount"].(float64)
- }
- if vv["午餐"]["amount"] != nil {
- lunchAmountTotal += vv["午餐"]["amount"].(float64)
- }
- if vv["晚餐"]["amount"] != nil {
- dinnerAmountTotal += vv["晚餐"]["amount"].(float64)
- }
- if vv["夜宵"]["amount"] != nil {
- supperAmountTotal += vv["夜宵"]["amount"].(float64)
- }
- if vv["合计"]["amount"] != nil {
- totalAmountTotal += vv["合计"]["amount"].(float64)
- }
- j++
- }
- xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{"总计", userTotal,
- breakFastTotal, breakFastAmountTotal,
- lunchTotal, lunchAmountTotal,
- dinnerTotal, dinnerAmountTotal,
- supperTotal, supperAmountTotal,
- totalTotal, totalAmountTotal,
- })
- sheetIndex++
- }
- xlsx.DeleteSheet("template") //删除模板表
- //将文件保存至服务器
- xlsx.SaveAs("./static" + downloadPath)
- break
- case 2:
- //商家分餐数据统计表
- xlsx, _ := excelize.OpenFile("./static/template/自营学校(商家分餐数据统计表).xlsx")
- fileName = "商家分餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- downloadPath = "/export/self_support_for_school/" + fileName
-
- //查询出所有的商家
- var merchantList []*model.Merchant
- err := db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&merchantList)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>1111Error:::", err.Error())
- return
- }
-
- //查询出所有的设备
- var deviceList []*model.Device
- err = db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>1111Error:::", err.Error())
- return
- }
- var merchantListMapping = map[int]model.Merchant{}
- var merchantDeviceListMapping = map[int]map[string]model.Device{}
- var deviceListMapping = map[string]model.Device{}
- var deviceNameArr []string
- var isHasDeviceName = map[string]bool{}
- for _, v := range deviceList {
- if merchantDeviceListMapping[v.MerchantId] == nil {
- merchantDeviceListMapping[v.MerchantId] = map[string]model.Device{}
- }
- merchantDeviceListMapping[v.MerchantId][v.DeviceSn] = *v
- deviceListMapping[v.DeviceSn] = *v
- if !isHasDeviceName[v.Name] {
- deviceNameArr = append(deviceNameArr, v.Name)
- isHasDeviceName[v.Name] = true
- }
- }
- for _, v := range merchantList {
- merchantListMapping[v.Id] = *v
- }
-
- var m []*db.SelfSupportForSchoolOrdWithUserIdentityV2
- sess := db.Db.Desc("self_support_for_school_ord.id").Where("self_support_for_school_ord.order_status =?", enum.SelfSupportForSchoolOrdOrderStatusForSuccess)
- if req.EnterpriseId != 0 {
- sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- _, err = sess.
- Join("LEFT", "enterprise", "self_support_for_school_ord.enterprise_id = enterprise.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
- return
- }
-
- //整合数据
- var data = map[string]map[string]map[string]map[string]map[string]float64{}
- for _, vv := range m {
- device := deviceListMapping[vv.SelfSupportForSchoolOrd.DeviceSn]
- shopName := merchantListMapping[device.MerchantId].Name
- deviceName := device.Name
- if data[vv.Enterprise.Name] == nil {
- data[vv.Enterprise.Name] = make(map[string]map[string]map[string]map[string]float64)
- }
- if data[vv.Enterprise.Name][shopName] == nil {
- data[vv.Enterprise.Name][shopName] = make(map[string]map[string]map[string]float64)
- }
- if data[vv.Enterprise.Name][shopName][deviceName] == nil {
- data[vv.Enterprise.Name][shopName][deviceName] = make(map[string]map[string]float64)
- }
-
- mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime)
- if data[vv.Enterprise.Name][shopName][deviceName][mealZh] == nil {
- data[vv.Enterprise.Name][shopName][deviceName][mealZh] = make(map[string]float64)
- }
- if data[vv.Enterprise.Name][shopName][deviceName]["合计"] == nil {
- data[vv.Enterprise.Name][shopName][deviceName]["合计"] = make(map[string]float64)
- }
- data[vv.Enterprise.Name][shopName][deviceName][mealZh]["num"]++
- data[vv.Enterprise.Name][shopName][deviceName][mealZh]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
- data[vv.Enterprise.Name][shopName][deviceName]["合计"]["num"]++
- data[vv.Enterprise.Name][shopName][deviceName]["合计"]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
- }
-
- xlsx.SetSheetRow("", "A1", &titleList)
- sheetIndex := 2 //第一个表是模板表
- for k, v := range data {
- if k == "" {
- k = "未知"
- }
- xlsx.NewSheet(k) //1、新建表格
- xlsx.CopySheet(1, sheetIndex)
- xlsx.SetSheetRow(k, "A1", &[]interface{}{"商 家 分 餐 数 据 统 计 表 " + "(" + req.StartDate + "至" + req.EndDate + ")"})
- j := 4 //表头前三行被占用了,只能从第四行开始
- var breakFastTotal, lunchTotal, dinnerTotal, supperTotal, totalTotal float64
- var breakFastAmountTotal, lunchAmountTotal, dinnerAmountTotal, supperAmountTotal, totalAmountTotal float64
- for kk, vv := range v {
- var startRow = 0
- var endRow = 0
- for _, device := range deviceNameArr {
- for kkk, vvv := range vv {
- if kkk == "" {
- kkk = k
- }
- if device == kkk {
- xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{kk, kkk,
- vvv["早餐"]["num"], vvv["早餐"]["amount"],
- vvv["午餐"]["num"], vvv["午餐"]["amount"],
- vvv["晚餐"]["num"], vvv["晚餐"]["amount"],
- vvv["夜宵"]["num"], vvv["夜宵"]["amount"],
- vvv["合计"]["num"], vvv["合计"]["amount"],
- })
-
- breakFastTotal += vvv["早餐"]["num"]
- lunchTotal += vvv["午餐"]["num"]
- dinnerTotal += vvv["晚餐"]["num"]
- supperTotal += vvv["夜宵"]["num"]
- totalTotal += vvv["合计"]["num"]
- breakFastAmountTotal += vvv["早餐"]["amount"]
- lunchAmountTotal += vvv["午餐"]["amount"]
- dinnerAmountTotal += vvv["晚餐"]["amount"]
- supperAmountTotal += vvv["夜宵"]["amount"]
- totalAmountTotal += vvv["合计"]["amount"]
-
- if startRow == 0 {
- startRow = j
- }
- endRow = j
- j++
- }
- }
- }
- xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{"", "合计",
- breakFastTotal, breakFastAmountTotal,
- lunchTotal, lunchAmountTotal,
- dinnerTotal, dinnerAmountTotal,
- supperTotal, supperAmountTotal,
- totalTotal, totalAmountTotal,
- })
- if startRow == 0 {
- startRow = j
- }
- endRow = j
- j++
-
- style, err := xlsx.NewStyle(`{"alignment":{"horizontal":"center", "vertical": "center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.MergeCell(k, "A"+utils.IntToStr(startRow), "A"+utils.IntToStr(endRow)) //合并单元格
- xlsx.SetCellStyle(k, "A"+utils.IntToStr(startRow), "A"+utils.IntToStr(endRow), style)
- }
- sheetIndex++
- }
- xlsx.DeleteSheet("template") //删除模板表
- //将文件保存至服务器
- xlsx.SaveAs("./static" + downloadPath)
- break
- case 3:
- //就餐数据统计表
- xlsx, _ := excelize.OpenFile("./static/template/自营学校(就餐数据统计表).xlsx")
- fileName = "就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- downloadPath = "/export/self_support_for_school/" + fileName
-
- //查询出所有的设备
- //var deviceList []*model.Device
- //err := db.Db.Where("enterprise_id != 0").Find(&deviceList)
- //if err != nil {
- // logx.Error(err)
- // println("<<<<SelfSupportForSchoolDataStatisticsExport2>>>>>1111Error:::", err.Error())
- // return
- //}
- //var deviceListMapping = map[string]model.Device{}
- //for _, v := range deviceList {
- // deviceListMapping[v.DeviceSn] = *v
- //}
-
- var m []*db.SelfSupportForSchoolOrdWithUserIdentity
- sess := db.Db.Desc("self_support_for_school_ord.id")
- if req.EnterpriseId != 0 {
- sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- _, err := sess.
- Join("LEFT", "user_identity", "self_support_for_school_ord.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").
- Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- return
- }
-
- //整合数据
- var data = map[string]map[string]map[string]map[string]float64{}
-
- date1, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- return
- }
- date2, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- return
- }
- diffDays := int(date2.Sub(date1).Hours() / 24)
- var dates []string
- for i := 0; i <= diffDays; i++ {
- date := date1.AddDate(0, 0, i)
- shopName := date.Format("2006-01-02")
- dates = append(dates, shopName)
- for _, vv := range m {
- tmpDate, err1 := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.FaceTime, time.Local)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
- return
- }
- fmt.Println(tmpDate.Format("2006-01-02"))
- if shopName == tmpDate.Format("2006-01-02") {
- if data[vv.Enterprise.Name] == nil {
- data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64)
- }
- if data[vv.Enterprise.Name][shopName] == nil {
- data[vv.Enterprise.Name][shopName] = make(map[string]map[string]float64)
- }
- mealZh := JudgeSelfSupportForMealTime(vv.SelfSupportForSchoolOrd.FaceTime)
- if data[vv.Enterprise.Name][shopName][mealZh] == nil {
- data[vv.Enterprise.Name][shopName][mealZh] = make(map[string]float64)
- }
- if data[vv.Enterprise.Name][shopName]["合计"] == nil {
- data[vv.Enterprise.Name][shopName]["合计"] = make(map[string]float64)
- }
- data[vv.Enterprise.Name][shopName][mealZh]["num"]++
- data[vv.Enterprise.Name][shopName][mealZh]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
- data[vv.Enterprise.Name][shopName]["合计"]["num"]++
- data[vv.Enterprise.Name][shopName]["合计"]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
- }
- }
- }
-
- xlsx.SetSheetRow("", "A1", &titleList)
- sheetIndex := 2 //第一个表是模板表
- for k, v := range data {
- if k == "" {
- k = "未知"
- }
- xlsx.NewSheet(k) //1、新建表格
- xlsx.CopySheet(1, sheetIndex)
- j := 4 //表头前三行被占用了,只能从第四行开始
- for _, date := range dates {
- for kk, vv := range v {
- if date == kk {
- xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{kk,
- vv["早餐"]["num"], vv["早餐"]["amount"],
- vv["午餐"]["num"], vv["午餐"]["amount"],
- vv["晚餐"]["num"], vv["晚餐"]["amount"],
- vv["夜宵"]["num"], vv["夜宵"]["amount"],
- vv["合计"]["num"], vv["合计"]["amount"],
- })
- j++
- }
- sheetIndex++
- }
- }
- }
- xlsx.DeleteSheet("template") //删除模板表
- //将文件保存至服务器
- xlsx.SaveAs("./static" + downloadPath)
- break
- case 4:
- //设备就餐数据统计表
- fileName = "设备就餐数据统计_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
- downloadPath = "/export/self_support_for_school/" + fileName
-
- //查询出所有的设备
- var deviceList []*model.Device
- if req.EnterpriseId == 0 {
- err := db.Db.Where("enterprise_id != 0").OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>1111Error:::", err.Error())
- return
- }
- } else {
- err := db.Db.Where("enterprise_id = ?", req.EnterpriseId).OrderBy("CONVERT(name USING gbk) ASC").Find(&deviceList)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>1111Error:::", err.Error())
- return
- }
- }
-
- date1, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- return
- }
- date2, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- return
- }
- diffDays := int(date2.Sub(date1).Hours() / 24)
-
- var deviceListMapping = map[string]model.Device{}
- //整合数据
- var data = map[string]map[string]map[string]map[string]float64{}
- var xlsFileName, xlsDownloadPath []string
- for _, v := range deviceList {
- deviceListMapping[v.DeviceSn] = *v
- var m []*db.SelfSupportForSchoolOrdWithUserIdentityV2
- sess := db.Db.Where("device_sn = ?", v.DeviceSn).And("enterprise_id =?", req.EnterpriseId).Desc("self_support_for_school_ord.id")
- if req.EnterpriseId != 0 {
- sess.And("self_support_for_school_ord.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("self_support_for_school_ord.face_time >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("self_support_for_school_ord.face_time <= ?", req.EndDate)
- }
- _, err = sess.Join("LEFT", "enterprise", "self_support_for_school_ord.enterprise_id = enterprise.id").FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- return
- }
- for _, vv := range m {
- tmpTime, err1 := time.ParseInLocation("2006-01-02 15:04:05", vv.SelfSupportForSchoolOrd.FaceTime, time.Local)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
- return
- }
- tmpDate := tmpTime.Format("2006-01-02")
- if data[vv.Enterprise.Name] == nil {
- data[vv.Enterprise.Name] = make(map[string]map[string]map[string]float64)
- }
- if data[vv.Enterprise.Name][v.Name] == nil {
- data[vv.Enterprise.Name][v.Name] = make(map[string]map[string]float64)
- }
- if data[vv.Enterprise.Name][v.Name][tmpDate] == nil {
- data[vv.Enterprise.Name][v.Name][tmpDate] = make(map[string]float64)
- }
- data[vv.Enterprise.Name][v.Name][tmpDate]["num"]++
- data[vv.Enterprise.Name][v.Name][tmpDate]["amount"] += utils.StrToFloat64(vv.SelfSupportForSchoolOrd.TradeAmount)
- }
- }
-
- for k1, v := range data {
- tmpFileName := k1 + "设备就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- tmpDownloadPath := "./static/export/self_support_for_school/" + tmpFileName
- xlsx := excelize.NewFile()
-
- var totalData = map[string]map[string]float64{}
- for _, device := range deviceList {
- for k2, vv := range v {
- if k2 == device.Name {
- var sumNum, sumAmount = float64(0), float64(0)
- xlsx.NewSheet(k2)
- titleList = []string{" 设 备 分 餐 数 据 统 计 表 "}
- xlsx.SetSheetRow(k2, "A1", &titleList)
- titleList = []string{"日 期", "消费笔数", "消费金额"}
- xlsx.SetSheetRow(k2, "A2", &titleList)
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.MergeCell(k2, "A1", "C1") //合并单元格
- xlsx.SetCellStyle(k2, "A1", "C1", style)
- xlsx.SetColWidth(k2, "A", "C", 20)
- j := 3 //表头前两行用了,只能从第三行开始
-
- for i := 0; i <= diffDays; i++ {
- date := date1.AddDate(0, 0, i).Format("2006-01-02")
- if vv[date] != nil {
- xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{date, vv[date]["num"], vv[date]["amount"]})
- sumNum += vv[date]["num"]
- sumAmount += vv[date]["amount"]
- } else {
- xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{date, 0, 0})
- }
- j++
- }
-
- xlsx.SetSheetRow(k2, "A"+strconv.Itoa(j), &[]interface{}{
- "合计", sumNum, sumAmount})
- if totalData[k2] == nil {
- totalData[k2] = map[string]float64{}
- }
- totalData[k2]["num"] = sumNum
- totalData[k2]["amount"] = sumAmount
- }
- }
- }
-
- //xlsx.NewSheet("所有档口")
- xlsx.SetSheetName("Sheet1", "所有档口")
- titleList = []string{" 设 备 分 餐 数 据 统 计 表 "}
- xlsx.SetSheetRow("所有档口", "A1", &titleList)
- titleList = []string{"名 称", "消费笔数", "消费金额"}
- xlsx.SetSheetRow("所有档口", "A2", &titleList)
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.MergeCell("所有档口", "A1", "C1") //合并单元格
- xlsx.SetCellStyle("所有档口", "A1", "C1", style)
- xlsx.SetColWidth("所有档口", "A", "C", 20)
- j := 3 //表头前两行用了,只能从第三行开始
- var totalNum, totalAmount float64
- for _, device := range deviceList {
- for key, val := range totalData {
- if key == device.Name {
- totalNum += val["num"]
- totalAmount += val["amount"]
- xlsx.SetSheetRow("所有档口", "A"+strconv.Itoa(j), &[]interface{}{key, val["num"], val["amount"]})
- j++
- }
- }
- }
- xlsx.SetSheetRow("所有档口", "A"+strconv.Itoa(j), &[]interface{}{"合计", totalNum, totalAmount})
-
- //xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
- //将文件保存至服务器
- err1 := xlsx.SaveAs(tmpDownloadPath)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
- xlsFileName = append(xlsFileName, tmpFileName)
- }
-
- archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- panic(err)
- }
- defer archive.Close()
-
- zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
- for k, v := range xlsDownloadPath {
- w, err1 := zipWriter.Create("设备就餐数据统计/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
- if err1 != nil {
- logx.Error(err1)
- println("<<<<SelfSupportForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- f, err1 := os.Open(v) //打开待压缩的文件
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- if _, err1 = io.Copy(w, f); err != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
- panic(err1)
- }
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
- panic(err1)
- }
- f.Close()
- os.RemoveAll(v) //TODO::移除源文件
- }
-
- zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
- if err != nil {
- panic(err)
- }
- break
- }
-
- //新增数据
- selfSupportForSchoolExportRecordsDb := db.SelfSupportForSchoolExportRecordsDb{}
- selfSupportForSchoolExportRecordsDb.Set()
- marshal, _ := json.Marshal(req)
- selfSupportForSchoolExportRecordsDb.SelfSupportForSchoolExportRecordsInsert(&model.SelfSupportForSchoolExportRecords{
- Name: fileName,
- DownloadPath: downloadPath,
- Kind: req.Kind,
- ReqContent: string(marshal),
- CreateAt: now.Format("2006-01-02 15:04:05"),
- UpdateAt: now.Format("2006-01-02 15:04:05"),
- })
- }
-
- func CentralKitchenForSchoolDataStatisticsExport(req md.CentralKitchenForSchoolDataStatisticsExportReq) {
- var titleList []string
- var fileName, downloadPath string
- var now = time.Now()
- for _, kind := range req.Kinds {
- switch kind {
- case 1:
- xlsx := excelize.NewFile()
- //订单列表
- fileName = "订单列表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
-
- //查找订单数据
- sess := db.Db.Desc("central_kitchen_for_school_package_ord.id")
- sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess)
- if req.EnterpriseId != 0 {
- sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity
- _, err := sess.
- Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").
- Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
- return
- }
-
- //查找预定数据
- var outTradeNoList []string
- for _, v := range m {
- outTradeNoList = append(outTradeNoList, v.OutTradeNo)
- }
- var mm []model.CentralKitchenForSchoolPackageOrdForReserve
- sess1 := db.Db.Desc("id")
- if req.EnterpriseId != 0 {
- sess1.And("enterprise_id = ?", req.EnterpriseId)
- }
- if len(req.MealKindList) > 0 {
- sess1.In("kind", req.MealKindList)
- }
- err = sess1.In("out_trade_no", outTradeNoList).Find(&mm)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
- return
- }
- var exportOutTradeNoList []string
- for _, v := range mm {
- exportOutTradeNoList = append(exportOutTradeNoList, v.OutTradeNo)
- }
-
- titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 订单表"}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- titleList = []string{"订单号", "学生姓名", "学校", "年级", "班级", "家长电话", "预定日期", "预定餐数", "订单价格", "支付时间", "订单状态"}
- xlsx.SetSheetRow("Sheet1", "A2", &titleList)
-
- xlsx.MergeCell("Sheet1", "A1", "K1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle("Sheet1", "A1", "K1", style)
- xlsx.SetColWidth("Sheet1", "A", "k", 20)
-
- j := 3 //表头前两行用了,只能从第三行开始
- for _, v := range m {
- if !utils.InArr(v.OutTradeNo, exportOutTradeNoList) {
- continue
- }
- var ordState string //订单状态(0:待支付 1:预约成功 2:退款中 3:部分退款 4:已退款 5:已完成)
- switch v.CentralKitchenForSchoolPackageOrd.OrdState {
- case enum.CentralKitchenForSchoolPackageOrdOrdStateForWait:
- ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForWait)
- break
- case enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess:
- ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForSuccess)
- break
- case enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding:
- ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunding)
- break
- case enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded:
- ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForPartRefunded)
- break
- case enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded:
- ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForRefunded)
- break
- case enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete:
- ordState = enum.CentralKitchenForSchoolPackageOrdOrdState.String(enum.CentralKitchenForSchoolPackageOrdOrdStateForComplete)
- break
- }
- //预定餐数、预定日期
- var list []*model.CentralKitchenForSchoolUserWithDay
- err1 := json.Unmarshal([]byte(v.CentralKitchenForSchoolPackageOrd.WithDayData), &list)
- if err1 != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport1>>>>>Error:::", err.Error())
- return
- }
- var reserveDays string
- for _, v1 := range list {
- reserveDays += v1.Date + ", "
- }
- if v.Grade.Name == "" {
- v.Grade.Name = "教师"
- }
- if v.Class.Name == "" {
- v.Class.Name = "教师"
- }
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.CentralKitchenForSchoolPackageOrd.OutTradeNo, v.CentralKitchenForSchoolPackageOrd.UserIdentityName, v.Enterprise.Name,
- v.Grade.Name, v.Class.Name, v.User.Phone, reserveDays, len(list), v.CentralKitchenForSchoolPackageOrd.TotalPrice, v.CentralKitchenForSchoolPackageOrd.CreateAt, ordState})
- j++
- }
- //将文件保存至服务器
- xlsx.SaveAs("./static" + downloadPath)
- break
- case 2:
- xlsx := excelize.NewFile()
- //退款申请表
- fileName = "退款申请表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
-
- //查找退款申请数据
- sess := db.Db.Desc("central_kitchen_for_school_user_refund_day.id")
- if req.EnterpriseId != 0 {
- sess.And("enterprise.id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
- }
- if len(req.MealKindList) > 0 {
- sess.In("central_kitchen_for_school_user_with_day.kind", req.MealKindList)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- var m []*db.CentralKitchenForSchoolUserRefundDayWithData
- _, err := sess.
- 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").
- 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").
- Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
- Join("LEFT", "user", "user_identity.uid = user.id").
- Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
- Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- Desc("central_kitchen_for_school_user_refund_day.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport2>>>>>Error:::", err.Error())
- return
- }
-
- titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 退款申请表"}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- titleList = []string{"学生姓名", "学校", "年级", "班级", "家长电话", "退款日期", "餐型", "退款金额", "退款状态", "支付时间", "退款操作时间"}
- xlsx.SetSheetRow("Sheet1", "A2", &titleList)
-
- xlsx.MergeCell("Sheet1", "A1", "K1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle("Sheet1", "A1", "K1", style)
- xlsx.SetColWidth("Sheet1", "A", "k", 20)
-
- j := 3 //表头前两行用了,只能从第三行开始
- for _, v := range m {
- var kind string //就餐类型(1:早餐 2:午餐 3:晚餐)
- switch v.CentralKitchenForSchoolUserWithDay.Kind {
- case enum.CentralKitchenForSchoolUserWithDayKindForBreakfast:
- kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast)
- break
- case enum.CentralKitchenForSchoolUserWithDayKindForLunch:
- kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForLunch)
- break
- case enum.CentralKitchenForSchoolUserWithDayKindForDinner:
- kind = enum.CentralKitchenForSchoolUserWithDayKind.String(enum.CentralKitchenForSchoolUserWithDayKindForDinner)
- break
- }
-
- var state string //状态(1:审核中 2:审核通过 3:审核拒绝 4:退款已完成)
- switch v.CentralKitchenForSchoolUserRefundDay.State {
- case enum.CentralKitchenForSchoolUserRefundDayStateForAuditing:
- state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditing)
- break
- case enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass:
- state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditPass)
- break
- case enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject:
- state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditReject)
- break
- case enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete:
- state = enum.CentralKitchenForSchoolUserRefundDayState.String(enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete)
- break
- }
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.CentralKitchenForSchoolPackageOrd.UserIdentityName, v.Enterprise.Name, v.Grade.Name, v.Class.Name, v.User.Phone,
- v.CentralKitchenForSchoolUserWithDay.Date, kind, v.CentralKitchenForSchoolUserRefundDay.Amount, state, v.CentralKitchenForSchoolPackageOrd.CreateAt, v.CentralKitchenForSchoolUserRefundDay.RefundDate})
- j++
- }
- //将文件保存至服务器
- xlsx.SaveAs("./static" + downloadPath)
- break
- case 3:
- //学校预定统计表
- fileName = "学校预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
-
- var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
- sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
- if req.EnterpriseId != 0 {
- sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
- }
-
- var months []time.Month
- if req.StartDate != "" {
- sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- _, sMonth, _ := sDate.Date()
- _, eMonth, _ := eDate.Date()
- diffMonth := sMonth - eMonth
- if diffMonth == 0 {
- //TODO::查询一个月
- months = append(months, sMonth)
- } else {
- for i := sMonth; i <= eMonth; i++ {
- months = append(months, i)
- }
- }
- }
- if len(months) > 0 {
- sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
- }
- //if req.EndDate != "" {
- // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
- //}
- if len(req.MealKindList) > 0 {
- sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- _, err := sess.
- 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").
- Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").
- Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- return
- }
-
- var ordNoArr, mealKindListArr []string
- for _, v := range m {
- ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
- }
-
- 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`"
- for _, v := range req.MealKindList {
- mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
- }
- sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
- nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
- var nativeResultsMap = map[string]map[int]int64{}
- for _, v := range nativeResults {
- if nativeResultsMap[v["ord_no"]] == nil {
- nativeResultsMap[v["ord_no"]] = make(map[int]int64)
- }
- nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"])
- }
-
- centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
- centralKitchenForSchoolUserWithDayDb.Set(0)
- var list = map[string]map[string]map[string]map[string]int64{}
- var xlsFileName, xlsDownloadPath []string
- for _, v := range m {
- if list[v.Enterprise.Name] == nil {
- list[v.Enterprise.Name] = make(map[string]map[string]map[string]int64)
- }
- if list[v.Enterprise.Name][v.Grade.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]int64)
- }
- if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]int64)
- }
-
- //count, err2 := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByOrdNo(
- // v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo,
- // enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling,
- // req.StartDate, req.EndDate, []int{v.CentralKitchenForSchoolPackageOrdForReserve.Kind})
- //if err2 != nil {
- // logx.Error(err)
- // println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- // return
- //}
- //time.Sleep(2 * time.Millisecond) // 2毫秒
- //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
- // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["breakfast"] += count
- //}
- //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
- // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["lunch"] += count
- //}
- //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
- // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["dinner"] += count
- //}
-
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["breakfast"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
- }
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["lunch"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
- }
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["dinner"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
- }
- }
-
- for k1, v1 := range list {
- xlsx := excelize.NewFile()
- tmpFileName := k1 + "学校预定统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") "}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- titleList = []string{"年级", "班级", "早餐", "午餐", "晚餐"}
-
- xlsx.SetSheetRow("Sheet1", "A2", &titleList)
- xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle("Sheet1", "A1", "E1", style)
- xlsx.SetColWidth("Sheet1", "A", "E", 20)
-
- j := 3 //表头前两行用了,只能从第三行开始
- var sumClassNum, sumBreakfast, sumLunch, sumDinner = int64(0), int64(0), int64(0), int64(0)
-
- tmpEnterpriseDb := db.EnterpriseDb{}
- tmpEnterpriseDb.Set()
- tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
- if err11 != nil {
- logx.Error(err11)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err11.Error())
- panic(err11)
- }
- tmpClassDb := db.ClassDb{}
- tmpClassDb.Set(0)
- classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- panic(err)
- }
- for _, class := range *classList {
- for k2, v2 := range v1 {
- if k2 == "" {
- //若年级为空,则为教师餐
- k2 = "教师餐"
- }
-
- for k3, v3 := range v2 {
- if class.Name != k3 {
- continue
- }
- if k3 == "" {
- //若班级为空,则为教师餐
- k3 = "教师餐"
- }
-
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
- k2, k3, v3["breakfast"], v3["lunch"], v3["dinner"]})
- sumClassNum++
- sumBreakfast += v3["breakfast"]
- sumLunch += v3["lunch"]
- sumDinner += v3["dinner"]
- j++
- }
- }
- }
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
- "合计", sumClassNum, sumBreakfast, sumLunch, sumDinner})
- //将文件保存至服务器
- err1 := xlsx.SaveAs(tmpDownloadPath)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
- panic(err1)
- }
- xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
- xlsFileName = append(xlsFileName, tmpFileName)
- }
-
- archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- defer archive.Close()
-
- zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
- for k, v := range xlsDownloadPath {
- w, err1 := zipWriter.Create("学校预定统计/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- f, err1 := os.Open(v) //打开待压缩的文件
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- if _, err1 = io.Copy(w, f); err != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
- panic(err1)
- }
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err1.Error())
- panic(err1)
- }
- f.Close()
- os.RemoveAll(v) //TODO::移除源文件
- }
-
- zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
- if err != nil {
- panic(err)
- }
- break
- case 4:
- //班级明细表
- fileName = "班级明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
- var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
- sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
- if req.EnterpriseId != 0 {
- sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
- }
- var months []time.Month
- if req.StartDate != "" {
- sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- _, sMonth, _ := sDate.Date()
- _, eMonth, _ := eDate.Date()
- diffMonth := sMonth - eMonth
- if diffMonth == 0 {
- //TODO::查询一个月
- months = append(months, sMonth)
- } else {
- for i := sMonth; i <= eMonth; i++ {
- months = append(months, i)
- }
- }
- }
- if len(months) > 0 {
- sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
- }
- //if req.EndDate != "" {
- // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
- //}
- if len(req.MealKindList) > 0 {
- sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- _, err := sess.
- 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").
- Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").
- Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- Asc("class.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- return
- }
-
- var ordNoArr, mealKindListArr []string
- for _, v := range m {
- ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
- }
-
- 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`"
- for _, v := range req.MealKindList {
- mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
- }
- sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
- nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
- var nativeResultsMap = map[string]map[int]int64{}
- for _, v := range nativeResults {
- if nativeResultsMap[v["ord_no"]] == nil {
- nativeResultsMap[v["ord_no"]] = make(map[int]int64)
- }
- nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"])
- }
-
- var list = map[string]map[string]map[string]map[string]map[string]int64{}
- var xlsFileName, xlsDownloadPath []string
- centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
- centralKitchenForSchoolUserWithDayDb.Set(0)
- for _, v := range m {
- if list[v.Enterprise.Name] == nil {
- list[v.Enterprise.Name] = make(map[string]map[string]map[string]map[string]int64)
- }
- if list[v.Enterprise.Name][v.Grade.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]map[string]int64)
- }
- if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]map[string]int64)
- }
- if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = make(map[string]int64)
- }
-
- //count, err2 := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByOrdNo(
- // v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo,
- // enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling,
- // req.StartDate, req.EndDate, []int{v.CentralKitchenForSchoolPackageOrdForReserve.Kind})
- //if err2 != nil {
- // logx.Error(err2)
- // println("<<<<SelfSupportForSchoolDataStatistics Export3>>>>>Error:::", err2.Error())
- // return
- //}
- //if count == 0 {
- // continue
- //}
- //time.Sleep(2 * time.Millisecond) // 2毫秒
- //
- //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
- // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["breakfast"] += count
- //}
- //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
- // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["lunch"] += count
- //}
- //if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
- // list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["dinner"] += count
- //}
-
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["breakfast"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
- }
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["lunch"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
- }
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["dinner"] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
- }
-
- }
-
- for k1, v1 := range list {
- xlsx := excelize.NewFile()
- tmpFileName := k1 + "班级明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
-
- //查询当前学校下的班级升序
- tmpEnterpriseDb := db.EnterpriseDb{}
- tmpEnterpriseDb.Set()
- tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
- if err11 != nil {
- logx.Error(err11)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err11.Error())
- panic(err11)
- }
- tmpClassDb := db.ClassDb{}
- tmpClassDb.Set(0)
- classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- panic(err)
- }
- for _, class := range *classList {
- for k2, v2 := range v1 {
- if k2 == "" {
- //若年级为空,则为教师餐
- continue
- }
- for k3, v3 := range v2 {
- if class.Name != k3 {
- continue
- }
- xlsx.NewSheet(k3)
- titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + ", " + k3 + "] 班级明细"}
- xlsx.SetSheetRow(k3, "A1", &titleList)
- titleList = []string{"姓名", "早餐", "午餐", "晚餐"}
- xlsx.SetSheetRow(k3, "A2", &titleList)
- xlsx.MergeCell(k3, "A1", "D1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle(k3, "A1", "D1", style)
- xlsx.SetColWidth(k3, "A", "D", 20)
-
- var sumBreakfast, sumLunch, sumDinner = int64(0), int64(0), int64(0)
- j := 3 //表头前两行用了,只能从第三行开始
- for k4, v4 := range v3 {
- if v4["breakfast"] == 0 && v4["lunch"] == 0 && v4["dinner"] == 0 {
- continue
- }
- xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
- k4, v4["breakfast"], v4["lunch"], v4["dinner"]})
- sumBreakfast += v4["breakfast"]
- sumLunch += v4["lunch"]
- sumDinner += v4["dinner"]
- j++
- }
- xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
- "合计", sumBreakfast, sumLunch, sumDinner})
- }
- }
- }
-
- //将文件保存至服务器
- xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
- err1 := xlsx.SaveAs(tmpDownloadPath)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
- panic(err1)
- }
- xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
- xlsFileName = append(xlsFileName, tmpFileName)
- }
-
- archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- panic(err)
- }
- defer archive.Close()
-
- zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
- for k, v := range xlsDownloadPath {
- w, err1 := zipWriter.Create("班级明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- f, err1 := os.Open(v) //打开待压缩的文件
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- if _, err1 = io.Copy(w, f); err != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
- panic(err1)
- }
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err1.Error())
- panic(err1)
- }
- f.Close()
- os.RemoveAll(v) //TODO::移除源文件
- }
-
- zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
- if err != nil {
- panic(err)
- }
- break
- case 5:
- xlsx := excelize.NewFile()
- //退款明细表
- fileName = "退款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
- sess := db.Db.Where("central_kitchen_for_school_user_refund_day.state =?", enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete).Desc("central_kitchen_for_school_user_refund_day.id")
- if req.EnterpriseId != 0 {
- sess.And("enterprise.id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
- }
- if len(req.MealKindList) > 0 {
- sess.In("central_kitchen_for_school_user_with_day.kind", req.MealKindList)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- var m []*db.CentralKitchenForSchoolUserRefundDayWithData
- _, err := sess.
- 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").
- 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").
- Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
- Join("LEFT", "user", "user_identity.uid = user.id").
- Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
- Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- Desc("central_kitchen_for_school_user_refund_day.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err.Error())
- return
- }
-
- var list = map[string]map[string]map[string]map[string]map[string]int{}
- var xlsFileName, xlsDownloadPath []string
- for _, v := range m {
- if list[v.Enterprise.Name] == nil {
- list[v.Enterprise.Name] = make(map[string]map[string]map[string]map[string]int)
- }
- if list[v.Enterprise.Name][v.Grade.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]map[string]int)
- }
- if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]map[string]int)
- }
- if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = make(map[string]int)
- }
-
- //就餐类型(1:早餐 2:午餐 3:晚餐)
- if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["breakfast"]++
- }
- if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["lunch"]++
- }
- if v.CentralKitchenForSchoolUserWithDay.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name]["dinner"]++
- }
- }
-
- for k1, v1 := range list {
- tmpFileName := k1 + "退款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
-
- for k2, v2 := range v1 {
- if k2 == "" {
- //若年级为空,则为教师餐
- continue
- }
-
- for k3, v3 := range v2 {
- xlsx.NewSheet(k3)
- titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " [" + k1 + ", " + k3 + "] 退款明细"}
- xlsx.SetSheetRow(k3, "A1", &titleList)
- titleList = []string{"姓名", "早餐", "午餐", "晚餐"}
- xlsx.SetSheetRow(k3, "A2", &titleList)
- xlsx.MergeCell(k3, "A1", "D1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle(k3, "A1", "D1", style)
- xlsx.SetColWidth(k3, "A", "D", 20)
-
- var sumBreakfast, sumLunch, sumDinner = 0, 0, 0
- j := 3 //表头前两行用了,只能从第三行开始
- for k4, v4 := range v3 {
- xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
- k4, v4["breakfast"], v4["lunch"], v4["dinner"]})
- sumBreakfast += v4["breakfast"]
- sumLunch += v4["lunch"]
- sumDinner += v4["dinner"]
- j++
- }
- xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
- "合计", sumBreakfast, sumLunch, sumDinner})
- }
- }
-
- //将文件保存至服务器
- xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
- err1 := xlsx.SaveAs(tmpDownloadPath)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
- panic(err1)
- }
- xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
- xlsFileName = append(xlsFileName, tmpFileName)
- }
-
- archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err.Error())
- panic(err)
- }
- defer archive.Close()
-
- zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
- for k, v := range xlsDownloadPath {
- w, err1 := zipWriter.Create("退款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- f, err1 := os.Open(v) //打开待压缩的文件
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- if _, err1 = io.Copy(w, f); err != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
- panic(err1)
- }
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport5>>>>>Error:::", err1.Error())
- panic(err1)
- }
- f.Close()
- os.RemoveAll(v) //TODO::移除源文件
- }
-
- zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
- if err != nil {
- panic(err)
- }
- break
- case 6:
- xlsx := excelize.NewFile()
- //收款统计表
- fileName = "收款统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
-
- //查找数据
- var m []model.Enterprise
- sess := db.Db.Desc("id")
- if req.EnterPriseKind != 0 {
- sess.And("kind = ?", req.EnterPriseKind)
- }
- if req.EnterpriseId != 0 {
- sess.And("id = ?", req.EnterpriseId)
- }
- err := sess.Find(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
- return
- }
-
- titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 收款统计表"}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- titleList = []string{"学校名称", "预定总费用", "退款总计", "实收费用", "预估费率"}
- xlsx.SetSheetRow("Sheet1", "A2", &titleList)
-
- xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle("Sheet1", "A1", "E1", style)
- xlsx.SetColWidth("Sheet1", "A", "E", 20)
-
- var incomeTotal, refundTotal, realityAmountTotal, rateFeeTotal float64
- j := 3 //表头前两行用了,只能从第三行开始
- for _, v := range m {
- var income, refund string
- //统计收入
- sql1 := fmt.Sprintf("SELECT sum(total_price) as total FROM central_kitchen_for_school_package_ord where state = 1 and enterprise_id = %d and pay_at >= '%s' and pay_at < '%s'", v.Id, req.StartDate, req.EndDate)
- mapArr1, err := db.QueryNativeString(db.Db, sql1)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
- return
- }
- if mapArr1 != nil {
- income = mapArr1[0]["total"]
- }
-
- //统计退款
- //查询出当前学校下所有的学生
- userIdentityDb := db.UserIdentityDb{}
- userIdentityDb.Set(0)
- userIdentities, _ := userIdentityDb.FindUserIdentityForEnterprise(v.Id)
- var userIdentityIds []string
- for _, v := range *userIdentities {
- userIdentityIds = append(userIdentityIds, utils.IntToStr(v.Id))
- }
- if len(userIdentityIds) != 0 {
- userIdentityStr := php2go.Implode(",", userIdentityIds)
- 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'",
- enum.CentralKitchenForSchoolUserRefundDayStateForAuditComplete, userIdentityStr, req.StartDate, req.EndDate)
- mapArr2, err := db.QueryNativeString(db.Db, sql2)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport6>>>>>Error:::", err.Error())
- return
- }
- if mapArr2 != nil {
- refund = mapArr2[0]["total"]
- }
- }
- realityAmount := utils.StrToFloat64(income) - utils.StrToFloat64(refund)
- rateFee := realityAmount * 0.002
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{v.Name, income, refund, realityAmount, rateFee})
- incomeTotal += utils.StrToFloat64(income)
- refundTotal += utils.StrToFloat64(refund)
- realityAmountTotal += realityAmount
- rateFeeTotal += rateFee
- j++
- }
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{"总计", incomeTotal, refundTotal, realityAmountTotal, rateFeeTotal})
- //将文件保存至服务器
- xlsx.SaveAs("./static" + downloadPath)
- break
- case 7:
- xlsx := excelize.NewFile()
- //班级收款明细表
- fileName = "班级收款明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
- //查找订单数据
- sess := db.Db.Desc("central_kitchen_for_school_package_ord.id")
- sess.And("central_kitchen_for_school_package_ord.state =?", enum.CentralKitchenForSchoolPackageOrdStateForSuccess).And("user_identity.identity = ?", enum.UserIdentityForCentralKitchenForStudent)
- if req.EnterpriseId != 0 {
- sess.And("central_kitchen_for_school_package_ord.enterprise_id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess.And("central_kitchen_for_school_package_ord.pay_at >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess.And("central_kitchen_for_school_package_ord.pay_at <= ?", req.EndDate)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- var m []*db.CentralKitchenForSchoolPackageOrdWithUserIdentity
- _, err := sess.
- Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").
- Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
- return
- }
-
- 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")
- if req.EnterpriseId != 0 {
- sess1.And("enterprise.id =?", req.EnterpriseId)
- }
- if req.StartDate != "" {
- sess1.And("central_kitchen_for_school_user_refund_day.create_at >= ?", req.StartDate)
- }
- if req.EndDate != "" {
- sess1.And("central_kitchen_for_school_user_refund_day.create_at <= ?", req.EndDate)
- }
-
- var mm []*db.CentralKitchenForSchoolUserRefundDayWithData
- _, err = sess1.
- 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").
- 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").
- Join("LEFT", "user_identity", "central_kitchen_for_school_user_with_day.identity_id = user_identity.id").
- Join("LEFT", "user", "user_identity.uid = user.id").
- Join("LEFT", "enterprise", "user_identity.enterprise_id = enterprise.id").
- Join("LEFT", "class_with_user", "user_identity.id = class_with_user.user_identity_id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- Desc("central_kitchen_for_school_user_refund_day.id").
- FindAndCount(&mm)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
- return
- }
-
- var list = map[string]map[string]map[string]map[string]float64{}
- for _, v := range m {
- if list[v.Enterprise.Name] == nil {
- list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64)
- }
- if list[v.Enterprise.Name][v.Grade.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64)
- }
- if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64)
- }
-
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["income"] += utils.StrToFloat64(v.CentralKitchenForSchoolPackageOrd.TotalPrice)
- }
- for _, v := range mm {
- if list[v.Enterprise.Name] == nil {
- list[v.Enterprise.Name] = make(map[string]map[string]map[string]float64)
- }
- if list[v.Enterprise.Name][v.Grade.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]float64)
- }
- if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]float64)
- }
-
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name]["refund"] += utils.StrToFloat64(v.CentralKitchenForSchoolUserRefundDay.Amount)
- }
-
- var xlsFileName, xlsDownloadPath []string
- for k1, v1 := range list {
- tmpFileName := k1 + "班级收款明细_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " (" + k1 + ") 班级收款明细"}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
- titleList = []string{"年级", "班级", "预定总费用", "退款总计"}
- xlsx.SetSheetRow("Sheet1", "A2", &titleList)
-
- xlsx.MergeCell("Sheet1", "A1", "D1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle("Sheet1", "A1", "D1", style)
- xlsx.SetColWidth("Sheet1", "A", "D", 20)
-
- j := 3 //表头前两行用了,只能从第三行开始
- var sumClassNum = int64(0)
- var sumIncome, sumRefund = float64(0), float64(0)
- for k2, v2 := range v1 {
- if k2 == "" {
- //若年级为空,则为教师餐
- continue
- }
- for k3, v3 := range v2 {
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{k2, k3, utils.Float64ToStr(v3["income"]), utils.Float64ToStr(v3["refund"])})
- sumClassNum++
- sumIncome += v3["income"]
- sumRefund += v3["refund"]
- j++
- }
- }
-
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
- "合计", sumClassNum, sumIncome, sumRefund})
- //将文件保存至服务器
- err1 := xlsx.SaveAs(tmpDownloadPath)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
- panic(err1)
- }
- xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
- xlsFileName = append(xlsFileName, tmpFileName)
- }
-
- archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err.Error())
- panic(err)
- }
- defer archive.Close()
-
- zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
- for k, v := range xlsDownloadPath {
- w, err1 := zipWriter.Create("班级收款明细/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- f, err1 := os.Open(v) //打开待压缩的文件
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- if _, err1 = io.Copy(w, f); err != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
- panic(err1)
- }
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport7>>>>>Error:::", err1.Error())
- panic(err1)
- }
- f.Close()
- os.RemoveAll(v) //TODO::移除源文件
- }
-
- zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
- if err != nil {
- panic(err)
- }
- break
- case 8:
- xlsx := excelize.NewFile()
- //学校预定数量统计表
- fileName = "学校预定数量统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
-
- var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
- sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
- if req.EnterpriseId != 0 {
- sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
- }
- var months []time.Month
- if req.StartDate != "" {
- sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- _, sMonth, _ := sDate.Date()
- _, eMonth, _ := eDate.Date()
- diffMonth := sMonth - eMonth
- if diffMonth == 0 {
- //TODO::查询一个月
- months = append(months, sMonth)
- } else {
- for i := sMonth; i <= eMonth; i++ {
- months = append(months, i)
- }
- }
- }
- if len(months) > 0 {
- sess.In("central_kitchen_for_school_package_ord_for_reserve.reserve_month", months)
- }
- //if req.EndDate != "" {
- // sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", req.EndDate)
- //}
- if len(req.MealKindList) > 0 {
- sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
- _, err := sess.
- 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").
- Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<SelfSupportForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- return
- }
-
- var ordNoArr, mealKindListArr []string
- for _, v := range m {
- ordNoArr = append(ordNoArr, v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo)
- }
- 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`"
- for _, v := range req.MealKindList {
- mealKindListArr = append(mealKindListArr, utils.IntToStr(v))
- }
- sDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- eDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- nativeSql = fmt.Sprintf(nativeSql, strings.Join(ordNoArr, ","), enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling, sDate.Format("2006-01-02"), eDate.Format("2006-01-02"), strings.Join(mealKindListArr, ","))
- nativeResults, err := db.QueryNativeString(db.Db, nativeSql)
- var nativeResultsMap = map[string]map[int]int64{}
- for _, v := range nativeResults {
- if nativeResultsMap[v["ord_no"]] == nil {
- nativeResultsMap[v["ord_no"]] = make(map[int]int64)
- }
- nativeResultsMap[v["ord_no"]][utils.StrToInt(v["kind"])] = utils.StrToInt64(v["total"])
- }
-
- var list = map[string]map[string]int64{}
- centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
- centralKitchenForSchoolUserWithDayDb.Set(0)
- for _, v := range m {
- if list[v.Enterprise.Name] == nil {
- list[v.Enterprise.Name] = map[string]int64{}
- }
- var count int64
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForBreakfast {
- count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
- list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForBreakfast]
- }
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForLunch {
- count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
- list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForLunch]
- }
- if v.CentralKitchenForSchoolPackageOrdForReserve.Kind == enum.CentralKitchenForSchoolUserWithDayKindForDinner {
- count = nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
- list[v.Enterprise.Name][enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()] += nativeResultsMap[v.CentralKitchenForSchoolPackageOrdForReserve.OutTradeNo][enum.CentralKitchenForSchoolUserWithDayKindForDinner]
- }
- list[v.Enterprise.Name]["count"] += count
- }
-
- titleList = []string{startDate.Format("2006-01-02") + "~~" + endDate.Format("2006-01-02") + " 预定数量统计表"}
- xlsx.SetSheetRow("Sheet1", "A1", &titleList)
-
- titleList = []string{"学校名称", "预定总数",
- enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String(),
- enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String(),
- enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String(),
- }
- xlsx.SetSheetRow("Sheet1", "A2", &titleList)
-
- xlsx.MergeCell("Sheet1", "A1", "E1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle("Sheet1", "A1", "E1", style)
- xlsx.SetColWidth("Sheet1", "A", "A", 30)
- xlsx.SetColWidth("Sheet1", "B", "E", 15)
- j := 3 //表头前两行用了,只能从第三行开始
- total := int64(0)
- total1 := int64(0)
- total2 := int64(0)
- total3 := int64(0)
- for k, v := range list {
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{k, v["count"],
- v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()],
- v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()],
- v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()]})
- total += v["count"]
- total1 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForBreakfast).String()]
- total2 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForLunch).String()]
- total3 += v[enum.CentralKitchenForSchoolUserWithDayKind(enum.CentralKitchenForSchoolUserWithDayKindForDinner).String()]
- j++
- }
- xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
- "合计", total, total1, total2, total3})
- //将文件保存至服务器
- xlsx.SaveAs("./static" + downloadPath)
- break
- case 10:
- //就餐数据统计表
- sTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.StartDate, time.Local)
- eTime, _ := time.ParseInLocation("2006-01-02 15:04:05", req.EndDate, time.Local)
- xls, _ := excelize.OpenFile("./static/template/央厨学校(就餐数据统计表).xlsx")
- fileName = "【" + sTime.Format("2006-01-02") + "~" + eTime.Format("2006-01-02") + "】就餐数据统计表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
-
- var list = map[string]map[string]map[string]float64{}
- var dates []string
-
- if req.StartDate != "" {
- centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
- centralKitchenForSchoolUserWithDayDb.Set(0)
- diffDays := int(eTime.Sub(sTime).Hours() / 24)
- for i := 0; i <= diffDays; i++ {
- date := sTime.AddDate(0, 0, i)
- dateName := date.Format("2006-01-02")
- dates = append(dates, dateName)
- for _, vv := range req.MealKindList {
- tmpSum, err := centralKitchenForSchoolUserWithDayDb.SumCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport9>>>>>Error:::", err.Error())
- panic(err)
- }
- tmpCount, err := centralKitchenForSchoolUserWithDayDb.CountCentralKitchenForSchoolUserWithDayByKind(req.EnterpriseId, dateName, dateName, vv, enum.CentralKitchenForSchoolUserWithDayStateForCancel, enum.CentralKitchenForSchoolUserWithDayStateForCanceling)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport9>>>>>Error:::", err.Error())
- panic(err)
- }
- if list[dateName] == nil {
- list[dateName] = map[string]map[string]float64{}
- }
- if list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] == nil {
- list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()] = map[string]float64{}
- }
- if list[dateName]["合计"] == nil {
- list[dateName]["合计"] = make(map[string]float64)
- }
-
- list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["sum"] = tmpSum
- list[dateName][enum.CentralKitchenForSchoolUserWithDayKind(vv).String()]["count"] = float64(tmpCount)
- list[dateName]["合计"]["sum"] += tmpSum
- list[dateName]["合计"]["count"] += float64(tmpCount)
- }
- }
- }
-
- //xls.SetSheetRow("", "A1", &titleList)
- //sheetIndex := 2 //第一个表是模板表
- //xls.NewSheet("sheet1") //1、新建表格
- //xls.CopySheet(1, sheetIndex)
- j := 4 //表头前三"早餐"行被占用了,只能从第四行开始
- var totalMap = map[string]float64{}
- for _, date := range dates {
- for kk, v := range list {
- if date == kk {
- xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{kk,
- v["早餐"]["count"], v["早餐"]["sum"],
- v["午餐"]["count"], v["午餐"]["sum"],
- v["晚餐"]["count"], v["晚餐"]["sum"],
- v["合计"]["count"], v["合计"]["sum"],
- })
- totalMap["breakfast_count"] += v["早餐"]["count"]
- totalMap["breakfast_sum"] += v["早餐"]["sum"]
- totalMap["lunch_count"] += v["午餐"]["count"]
- totalMap["lunch_sum"] += v["午餐"]["sum"]
- totalMap["dinner_count"] += v["晚餐"]["count"]
- totalMap["dinner_sum"] += v["晚餐"]["sum"]
- totalMap["total_count"] += v["合计"]["count"]
- totalMap["total_sum"] += v["合计"]["sum"]
- j++
- }
- }
- }
- //xls.DeleteSheet("template") //删除模板表
-
- xls.SetSheetRow("template", "A"+strconv.Itoa(j), &[]interface{}{"总计",
- totalMap["breakfast_count"], totalMap["breakfast_sum"],
- totalMap["lunch_count"], totalMap["lunch_sum"],
- totalMap["dinner_count"], totalMap["dinner_sum"],
- totalMap["total_count"], totalMap["total_sum"],
- })
- //将文件保存至服务器
- xls.SaveAs("./static" + downloadPath)
- break
- }
-
- //新增数据
- centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{}
- centralKitchenForSchoolExportRecordsDb.Set()
- marshal, _ := json.Marshal(req)
- centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{
- Name: fileName,
- DownloadPath: downloadPath,
- Kind: kind,
- ReqContent: string(marshal),
- CreateAt: now.Format("2006-01-02 15:04:05"),
- UpdateAt: now.Format("2006-01-02 15:04:05"),
- })
- }
- }
-
- func CentralKitchenForSchoolDataStatisticsContrast(req md.CentralKitchenForSchoolDataStatisticsContrastReq) {
- var titleList []string
- var fileName, downloadPath string
- var now = time.Now()
-
- xlsx := excelize.NewFile()
- //数据对比
- fileName = "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".zip"
- downloadPath = "/export/central_kitchen_for_school/" + fileName
-
- var m []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
- sess := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
- if req.EnterpriseId != 0 {
- sess.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
- }
- if req.Date1[0] != "" {
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local)
- sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02"))
- }
- if req.Date1[1] != "" {
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[1], time.Local)
- sess.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02"))
- }
- if len(req.MealKindList) > 0 {
- sess.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
- }
- if req.EnterPriseKind != 0 {
- sess.And("enterprise.kind = ?", req.EnterPriseKind)
- }
-
- _, err := sess.
- 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").
- Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").
- Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- FindAndCount(&m)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
- return
- }
-
- var m1 []*db.CentralKitchenForSchoolPackageOrdForReserveWithUserIdentity
- sess1 := db.Db.Desc("central_kitchen_for_school_package_ord_for_reserve.id")
- if req.EnterpriseId != 0 {
- sess1.And("central_kitchen_for_school_package_ord_for_reserve.enterprise_id =?", req.EnterpriseId)
- }
- if req.Date2[0] != "" {
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local)
- sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start >= ?", startDate.Format("2006-01-02"))
- }
- if req.Date2[1] != "" {
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[1], time.Local)
- sess1.And("central_kitchen_for_school_package_ord_for_reserve.meal_time_start <= ?", endDate.Format("2006-01-02"))
- }
- if len(req.MealKindList) > 0 {
- sess1.In("central_kitchen_for_school_package_ord_for_reserve.kind", req.MealKindList)
- }
- _, err1 := sess1.
- 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").
- Join("LEFT", "user_identity", "central_kitchen_for_school_package_ord_for_reserve.user_identity_id = user_identity.id").
- Join("LEFT", "enterprise", "enterprise.id = user_identity.enterprise_id").
- Join("LEFT", "user", "user.id = user_identity.uid").
- Join("LEFT", "class_with_user", "class_with_user.user_identity_id = user_identity.id").
- Join("LEFT", "class", "class_with_user.class_id = class.id").
- Join("LEFT", "grade", "class.grade_id = grade.id").
- FindAndCount(&m1)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
- return
- }
-
- var list = map[string]map[string]map[string]map[string]string{}
- for _, v := range m {
- if list[v.Enterprise.Name] == nil {
- list[v.Enterprise.Name] = make(map[string]map[string]map[string]string)
- }
- if list[v.Enterprise.Name][v.Grade.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string)
- }
- if list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string)
- }
- list[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone
- }
-
- var list1 = map[string]map[string]map[string]map[string]string{}
- for _, v := range m1 {
- if list1[v.Enterprise.Name] == nil {
- list1[v.Enterprise.Name] = make(map[string]map[string]map[string]string)
- }
- if list1[v.Enterprise.Name][v.Grade.Name] == nil {
- list1[v.Enterprise.Name][v.Grade.Name] = make(map[string]map[string]string)
- }
- if list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] == nil {
- list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name] = make(map[string]string)
- }
- list1[v.Enterprise.Name][v.Grade.Name][v.Class.Name][v.UserIdentity.Name] = v.User.Phone
- }
-
- var xlsFileName, xlsDownloadPath []string
- for k1, v1 := range list {
- tmpFileName := k1 + "数据对比_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
- tmpDownloadPath := "./static/export/central_kitchen_for_school/" + tmpFileName
- startDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date1[0], time.Local)
- endDate, _ := time.ParseInLocation("2006-01-02 15:04:05", req.Date2[0], time.Local)
-
- //查询当前学校下的班级升序
- tmpEnterpriseDb := db.EnterpriseDb{}
- tmpEnterpriseDb.Set()
- tmpEnterprise, err11 := tmpEnterpriseDb.GetEnterpriseByName(k1)
- if err11 != nil {
- logx.Error(err11)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err11.Error())
- panic(err11)
- }
- tmpClassDb := db.ClassDb{}
- tmpClassDb.Set(0)
- classList, err := tmpClassDb.FindClassAscByEnterprise(tmpEnterprise.Id)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport4>>>>>Error:::", err.Error())
- panic(err)
- }
- for _, class := range *classList {
- for k2, v2 := range v1 {
- if k2 == "" {
- //若年级为空,则为教师
- continue
- }
- for k3, v3 := range v2 {
- if class.Name != k3 {
- continue
- }
- xlsx.NewSheet(k3)
- titleList = []string{startDate.Format("2006-01") + "~~" + endDate.Format("2006-01") + " [" + k1 + ", " + k3 + "] 订餐数据对比"}
- xlsx.SetSheetRow(k3, "A1", &titleList)
- titleList = []string{"姓名", "家长联系电话"}
- xlsx.SetSheetRow(k3, "A2", &titleList)
- xlsx.MergeCell(k3, "A1", "B1") //合并单元格
- style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFF00"],"pattern":1}, "alignment":{"horizontal":"center"}}`)
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsExport3>>>>>Error:::", err.Error())
- panic(err)
- }
- xlsx.SetCellStyle(k3, "A1", "B1", style)
- xlsx.SetColWidth(k3, "A", "B", 40)
-
- j := 2 //表头被第一行用了,只能从第二行开始
- for k4, v4 := range v3 {
- //TODO::判断当前用户是否在新的月份里面
- fmt.Println("11111111111111", list1[k1])
- fmt.Println("22222222222222", list1[k1][k2])
- fmt.Println("33333333333333", list1[k1][k2][k3])
- fmt.Println("44444444444444", list1[k1][k2][k3][k4])
- if list1[k1] == nil || list1[k1][k2] == nil || list1[k1][k2][k3] == nil || list1[k1][k2][k3][k4] == "" {
- xlsx.SetSheetRow(k3, "A"+strconv.Itoa(j), &[]interface{}{
- k4, v4})
- j++
- }
- }
- }
- }
- }
-
- //将文件保存至服务器
- xlsx.DeleteSheet("Sheet1") //TODO::只能放这里删除
- err1 := xlsx.SaveAs(tmpDownloadPath)
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
- panic(err1)
- }
- xlsDownloadPath = append(xlsDownloadPath, tmpDownloadPath)
- xlsFileName = append(xlsFileName, tmpFileName)
- }
-
- archive, err := os.Create("./static" + downloadPath) //第一步,创建 zip 文件
- if err != nil {
- logx.Error(err)
- println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err.Error())
- panic(err)
- }
- defer archive.Close()
-
- zipWriter := zip.NewWriter(archive) //第二步,创建一个新的 *Writer 对象
- for k, v := range xlsDownloadPath {
- w, err1 := zipWriter.Create("数据对比/" + xlsFileName[k]) //向 zip 文件中添加一个文件,返回一个待压缩的文件内容应写入的 Writer
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- f, err1 := os.Open(v) //打开待压缩的文件
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
- panic(err1)
- }
-
- if _, err1 = io.Copy(w, f); err != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
- panic(err1)
- }
- if err1 != nil {
- logx.Error(err1)
- println("<<<<CentralKitchenForSchoolDataStatisticsContrast>>>>>Error:::", err1.Error())
- panic(err1)
- }
- f.Close()
- os.RemoveAll(v) //TODO::移除源文件
- }
-
- zipWriter.Close() // 第四步,关闭 zip writer,将所有数据写入指向基础 zip 文件的数据流
- if err != nil {
- panic(err)
- }
-
- //新增数据
- centralKitchenForSchoolExportRecordsDb := db.CentralKitchenForSchoolExportRecordsDb{}
- centralKitchenForSchoolExportRecordsDb.Set()
- marshal, _ := json.Marshal(req)
- centralKitchenForSchoolExportRecordsDb.CentralKitchenForSchoolExportRecordsInsert(&model.CentralKitchenForSchoolExportRecords{
- Name: fileName,
- DownloadPath: downloadPath,
- Kind: 9, //数据对比
- ReqContent: string(marshal),
- CreateAt: now.Format("2006-01-02 15:04:05"),
- UpdateAt: now.Format("2006-01-02 15:04:05"),
- })
- }
-
- func JudgeSelfSupportForMealTime(mealDate string) (mealZh string) {
- mealZh = "未知"
- mealTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealDate, time.Local)
- for _, v := range md.SelfSupportForMealTimeMapping {
- //判断时间大小
- tmpFromTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["from"]+":00", time.Local)
- tmpToTime, _ := time.ParseInLocation("2006-01-02 15:04:05", mealTime.Format("2006-01-02")+" "+v["to"]+":00", time.Local)
- fmt.Println(">>>>>>>>>>>>>", mealTime.After(tmpFromTime))
- fmt.Println("<<<<<<<<<<<<<", mealTime.Before(tmpToTime))
- if mealTime.After(tmpFromTime) && mealTime.Before(tmpToTime) {
- mealZh = v["name"]
- }
- }
- return
- }
|