Browse Source

update 导出

master
dengbiao 6 months ago
parent
commit
2b7116d513
9 changed files with 587 additions and 7 deletions
  1. +121
    -0
      app/admin/hdl/hdl_data_statistics.go
  2. +62
    -0
      app/admin/md/md_export_records.go
  3. +260
    -0
      app/admin/svc/svc_data_statisstics.go
  4. +107
    -0
      app/db/db_export_records.go
  5. +9
    -0
      app/db/db_order_list.go
  6. +11
    -0
      app/db/model/export_records.go
  7. +13
    -6
      app/router/admin_router.go
  8. +4
    -1
      k8s/deployment-prd.yaml
  9. BIN
     

+ 121
- 0
app/admin/hdl/hdl_data_statistics.go View File

@@ -0,0 +1,121 @@
package hdl

import (
"applet/app/admin/md"
"applet/app/admin/svc"
"applet/app/bigData/lib/validate"
"applet/app/db"
"applet/app/e"
"fmt"
"github.com/gin-gonic/gin"
"os"
)

func DataStatisticsList(c *gin.Context) {
var req md.ExportRecordsListReq
err := c.ShouldBindJSON(&req)
if err != nil {
err = validate.HandleValidateErr(err)
err1 := err.(e.E)
e.OutErr(c, err1.Code, err1.Error())
return
}
if req.Limit == 0 {
req.Limit = 10
}
if req.Page == 0 {
req.Page = 10
}

exportRecordsDb := db.ExportRecordsDb{}
exportRecordsDb.Set()
list, total, err := exportRecordsDb.ExportRecordsExportRecordsList(req)
if err != nil {
e.OutErr(c, e.ERR_DB_ORM, err.Error())
return
}

e.OutSuc(c, map[string]interface{}{
"list": list,
"total": total,
"kind": []map[string]interface{}{
{
"name": "商品销售明细表",
"value": 1,
},
{
"name": "对账单",
"value": 2,
},
},
}, nil)
return
}

func DataStatisticsDelete(c *gin.Context) {
var req struct {
Ids []int `json:"ids"`
}
err := c.ShouldBindJSON(&req)
if err != nil {
err = validate.HandleValidateErr(err)
err1 := err.(e.E)
e.OutErr(c, err1.Code, err1.Error())
return
}

for _, id := range req.Ids {
exportRecordsDb := db.ExportRecordsDb{}
exportRecordsDb.Set()
exportRecords, err1 := exportRecordsDb.GetExportRecordsExportRecords(id)
if err1 != nil {
e.OutErr(c, e.ERR_DB_ORM, err1.Error())
return
}
if exportRecords == nil {
e.OutErr(c, e.ERR_NO_DATA, "未查询到相关记录")
return
}
err = os.RemoveAll("./data/export/" + exportRecords.DownloadPath) //移除文件
if err != nil {
fmt.Println("err>>>>>>>>>>>>>>", err.Error())
}
_, err2 := exportRecordsDb.ExportRecordsExportRecordsDelete(id)
if err2 != nil {
e.OutErr(c, e.ERR_DB_ORM, err2.Error())
return
}
}

e.OutSuc(c, "success", nil)
return
}

func DataStatisticsExport(c *gin.Context) {
var req md.DataStatisticsExportReq
err := c.ShouldBindJSON(&req)
if err != nil {
err = validate.HandleValidateErr(err)
err1 := err.(e.E)
e.OutErr(c, err1.Code, err1.Error())
return
}

if req.EnterpriseId != 0 {
enterpriseDb := db.EnterpriseDb{}
enterpriseDb.Set()
enterprise, err1 := enterpriseDb.GetEnterprise(req.EnterpriseId)
if err1 != nil {
e.OutErr(c, e.ERR_DB_ORM, err1.Error())
return
}
req.EnterpriseName = enterprise.Name
}

go svc.DataStatisticsExport(req)

e.OutSuc(c, map[string]interface{}{
"msg": "导出成功,请稍后刷新数据列表",
}, nil)
return
}

+ 62
- 0
app/admin/md/md_export_records.go View File

@@ -0,0 +1,62 @@
package md

type CentralKitchenForSchoolExportRecordsListReq struct {
Page int `json:"page" label:"页码"`
Kind int `json:"kind" label:"导出类型"`
Limit int `json:"limit" label:"每页数量"`
StartDate string `json:"start_date" label:"起始时间"`
EndDate string `json:"end_date" label:"截止时间"`
}

type CentralKitchenForSchoolDataStatisticsExportReq struct {
Kinds []int `json:"kinds" binding:"required" label:"导出类型"`
EnterPriseKind int `json:"enterprise_kind" binding:"required" label:"校企类型"`
StartDate string `json:"start_date" binding:"required" label:"起始时间"`
EndDate string `json:"end_date" binding:"required" label:"截止时间"`
MealKindList []int `json:"meal_kind_list" label:"就餐类型(1:早餐 2:午餐 3:晚餐)"`
EnterpriseId int `json:"enterprise_id" label:"校企id"`
EnterpriseName string `json:"enterprise_name" label:"校企名称"`
}

type CentralKitchenForSchoolDataStatisticsContrastReq struct {
Date1 []string `json:"date_1" binding:"required" label:"起始时间"`
Date2 []string `json:"date_2" binding:"required" label:"截止时间"`
MealKindList []int `json:"meal_kind_list" label:"就餐类型(1:早餐 2:午餐 3:晚餐)"`
EnterpriseId int `json:"enterprise_id" label:"校企id"`
EnterPriseKind int `json:"enterprise_kind" binding:"required" label:"校企类型"`
EnterpriseName string `json:"enterprise_name" label:"校企名称"`
}

type NursingHomeExportRecordsListReq struct {
Page int `json:"page" label:"页码"`
Kind int `json:"kind" label:"导出类型"`
Limit int `json:"limit" label:"每页数量"`
StartDate string `json:"start_date" label:"起始时间"`
EndDate string `json:"end_date" label:"截止时间"`
}

type NursingHomeDataStatisticsExportReq struct {
Kind int `json:"kind" binding:"required" label:"导出类型"`
StartDate string `json:"start_date" binding:"required" label:"起始时间"`
EndDate string `json:"end_date" binding:"required" label:"截止时间"`
EnterpriseId int `json:"enterprise_id" label:"校企id"`
EnterpriseName string `json:"enterprise_name" label:"校企名称"`
}

type ExportRecordsListReq struct {
Page int `json:"page" label:"页码"`
Kind int `json:"kind" label:"导出类型"`
Limit int `json:"limit" label:"每页数量"`
StartDate string `json:"start_date" label:"起始时间"`
EndDate string `json:"end_date" label:"截止时间"`
}

type DataStatisticsExportReq struct {
Kind int `json:"kind" binding:"required" label:"导出类型"`
StartDate string `json:"start_date" label:"起始时间"`
EndDate string `json:"end_date" label:"截止时间"`
DateForStartDate string `json:"date_for_start_date" label:"送达-起始时间"`
DateForEndDate string `json:"date_for_end_date" label:"送达-截止时间"`
EnterpriseId int `json:"enterprise_id" label:"校企id"`
EnterpriseName string `json:"enterprise_name" label:"校企名称"`
}

+ 260
- 0
app/admin/svc/svc_data_statisstics.go View File

@@ -0,0 +1,260 @@
package svc

import (
"applet/app/admin/md"
"applet/app/db"
"applet/app/db/model"
"applet/app/utils"
"applet/app/utils/logx"
"encoding/json"
"github.com/360EntSecGroup-Skylar/excelize"
"strconv"
"time"
)

func DataStatisticsExport(req md.DataStatisticsExportReq) {
var fileName, downloadPath string
var now = time.Now()
switch req.Kind {
case 1:
//商品销售明细表
fileName = "商品销售明细表_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
downloadPath = "./data/export/" + fileName

//查询数据
eg := db.Db
list, _ := db.GetOrderListExport(eg, map[string]string{
"start_at": req.StartDate,
"end_at": req.EndDate,
"enterprise_id": strconv.Itoa(req.EnterpriseId),
"start_at_for_date": utils.TimeParseStd(req.DateForStartDate).Format("20060102"),
"end_at_for_date": utils.TimeParseStd(req.DateForEndDate).Format("20060102"),
})
xlsx, _ := excelize.OpenFile("./static/template/商品销售明细表.xlsx")
var data = map[string]map[int64]map[string]string{}
if list != nil {
enterpriseIds := make([]int, 0)
for _, v := range *list {
enterpriseIds = append(enterpriseIds, v.EnterpriseId)
}
enterpriseMap := db.GetEnterpriseMore(eg, enterpriseIds)

for _, v := range *list {
enterpriseName := "-"
_, ok := enterpriseMap[v.EnterpriseId]
if ok {
enterpriseName = enterpriseMap[v.EnterpriseId].Name
}
if data[enterpriseName] == nil {
data[enterpriseName] = make(map[int64]map[string]string)
}
if data[enterpriseName][v.Oid] == nil {
data[enterpriseName][v.Oid] = make(map[string]string)
}
//TODO:: 查找 `order_goods`
var orderGoods []model.OrderGoods
err := eg.Where("oid = ?", v.Oid).Find(&orderGoods)
if err != nil {
logx.Error(err)
println("<<<<DataStatisticsExport111111>>>>>Error:::", err.Error())
return
}
for _, vv := range orderGoods {
data[enterpriseName][v.Oid]["date"] = v.CreateAt.Format("2006-01-02")
data[enterpriseName][v.Oid]["goods_name"] = vv.GoodsTitle
skuData := make([]md.Sku, 0)
json.Unmarshal([]byte(vv.Sku), &skuData)
skuStr := ""
for _, v1 := range skuData {
if skuStr != "" {
skuStr += ";"
}
skuStr += v1.Value
}
data[enterpriseName][v.Oid]["sku_str"] = skuStr
data[enterpriseName][v.Oid]["num"] = utils.IntToStr(vv.Num)
}
}
}
sheetIndex := 2 //第一个表是模板表
xlsx.NewSheet("Sheet1") //新建表格
xlsx.CopySheet(1, sheetIndex)
xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(2), &[]interface{}{
"日期:" + utils.TimeParseStd(req.StartDate).Format("2006-01-02") + " ~ " + utils.TimeParseStd(req.EndDate).Format("2006-01-02"),
})

j := 4 //表头前三行被占用了,只能从第四行开始
for k, v := range data {
var total = 0
for kk, vv := range v {
xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
vv["date"],
utils.Int64ToStr(kk),
k,
vv["goods_name"],
vv["sku_str"],
vv["num"],
})
xlsx.SetRowHeight("Sheet1", j, 18)
total += utils.StrToInt(vv["num"])
j++
}

style, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFFCC"],"pattern":1}, "alignment":{"horizontal":"center", "vertical": "center"}}`)
if err != nil {
logx.Error(err)
println("<<<<SupportForSchoolDataStatisticsExport>>>>>Error:::", err.Error())
panic(err)
}
xlsx.MergeCell("Sheet1", "A"+strconv.Itoa(j), "F"+strconv.Itoa(j)) //合并单元格
xlsx.SetCellStyle("Sheet1", "A"+strconv.Itoa(j), "F"+strconv.Itoa(j), style)
xlsx.SetSheetRow("Sheet1", "A"+strconv.Itoa(j), &[]interface{}{
k + " 汇总: " + utils.IntToStr(total),
})
xlsx.SetRowHeight("Sheet1", j, 20)
j++
}

xlsx.DeleteSheet("template") //删除模板表
//将文件保存至服务器
xlsx.SaveAs(downloadPath)
break
case 2:
//对账单
fileName = "对账单_" + utils.Int64ToStr(now.UnixMilli()) + ".xlsx"
downloadPath = "./data/export/" + fileName

//查询数据
eg := db.Db
list, _ := db.GetOrderListExport(eg, map[string]string{
"start_at": req.StartDate,
"end_at": req.EndDate,
"enterprise_id": strconv.Itoa(req.EnterpriseId),
"start_at_for_date": utils.TimeParseStd(req.DateForStartDate).Format("20060102"),
"end_at_for_date": utils.TimeParseStd(req.DateForEndDate).Format("20060102"),
})
xlsx, _ := excelize.OpenFile("./static/template/对账单.xlsx")
var data = map[string]map[int64]map[string]string{}
if list != nil {
enterpriseIds := make([]int, 0)
for _, v := range *list {
enterpriseIds = append(enterpriseIds, v.EnterpriseId)
}
enterpriseMap := db.GetEnterpriseMore(eg, enterpriseIds)

for _, v := range *list {
enterpriseName := "-"
_, ok := enterpriseMap[v.EnterpriseId]
if ok {
enterpriseName = enterpriseMap[v.EnterpriseId].Name
}
if data[enterpriseName] == nil {
data[enterpriseName] = make(map[int64]map[string]string)
}
if data[enterpriseName][v.Oid] == nil {
data[enterpriseName][v.Oid] = make(map[string]string)
}
//TODO:: 查找 `order_goods`
var orderGoods []model.OrderGoods
err := eg.Where("oid = ?", v.Oid).Find(&orderGoods)
if err != nil {
logx.Error(err)
println("<<<<DataStatisticsExport111111>>>>>Error:::", err.Error())
return
}
for _, vv := range orderGoods {
data[enterpriseName][v.Oid]["date"] = v.CreateAt.Format("2006-01-02")
data[enterpriseName][v.Oid]["goods_name"] = vv.GoodsTitle
skuData := make([]md.Sku, 0)
json.Unmarshal([]byte(vv.Sku), &skuData)
skuStr := ""
for _, v1 := range skuData {
if skuStr != "" {
skuStr += ";"
}
skuStr += v1.Value
}
data[enterpriseName][v.Oid]["sku_str"] = skuStr
data[enterpriseName][v.Oid]["num"] = utils.IntToStr(vv.Num)
data[enterpriseName][v.Oid]["price"] = vv.Price
}
}
}

sheetIndex := 2 //第一个表是模板表
for k, v := range data {
xlsx.NewSheet(k) //新建表格
xlsx.CopySheet(1, sheetIndex)
xlsx.SetSheetRow(k, "A"+strconv.Itoa(2), &[]interface{}{
"客户: " + k,
})
xlsx.SetSheetRow(k, "A"+strconv.Itoa(5), &[]interface{}{
"对账单日期:" + utils.TimeParseStd(req.StartDate).Format("2006-01-02") + " ~ " + utils.TimeParseStd(req.EndDate).Format("2006-01-02"),
})
j := 7 //表头前三行被占用了,只能从第四行开始
var total, totalAmount float64
for kk, vv := range v {
amount := utils.StrToFloat64(vv["num"]) * utils.StrToFloat64(vv["price"])
xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{
vv["date"],
utils.Int64ToStr(kk),
k,
vv["goods_name"],
vv["sku_str"],
vv["num"],
vv["price"],
utils.StrToFloat64(vv["num"]) * utils.StrToFloat64(vv["price"]),
})
xlsx.SetRowHeight("k", j, 18)
total += utils.StrToFloat64(vv["num"])
totalAmount += amount
style, err := xlsx.NewStyle(`{"alignment":{"horizontal":"center", "vertical": "center"}}`)
if err != nil {
logx.Error(err)
println("<<<<SupportForSchoolDataStatisticsExport>>>>>Error:::", err.Error())
panic(err)
}
xlsx.SetCellStyle(k, "A"+strconv.Itoa(j), "H"+strconv.Itoa(j), style)
j++
}

style1, err := xlsx.NewStyle(`{"fill":{"type":"pattern","color":["FFFFCC"],"pattern":1}, "alignment":{"horizontal":"center", "vertical": "center"}}`)
if err != nil {
logx.Error(err)
println("<<<<SupportForSchoolDataStatisticsExport>>>>>Error:::", err.Error())
panic(err)
}
xlsx.SetCellStyle(k, "A"+strconv.Itoa(j), "H"+strconv.Itoa(j), style1)
xlsx.SetSheetRow(k, "A"+strconv.Itoa(j), &[]interface{}{
"合计",
"",
"",
"",
"",
total,
"",
totalAmount,
})
xlsx.SetRowHeight("k", j, 20)
sheetIndex++
}

xlsx.DeleteSheet("template") //删除模板表
//将文件保存至服务器
xlsx.SaveAs(downloadPath)
break
}

//新增数据
exportRecordsDb := db.ExportRecordsDb{}
exportRecordsDb.Set()
marshal, _ := json.Marshal(req)
exportRecordsDb.ExportRecordsExportRecordsInsert(&model.ExportRecords{
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"),
})
}

+ 107
- 0
app/db/db_export_records.go View File

@@ -0,0 +1,107 @@
package db

import (
"applet/app/admin/md"
"applet/app/db/model"
"applet/app/utils/logx"
"reflect"
"xorm.io/xorm"
)

type ExportRecordsDb struct {
Db *xorm.Engine `json:"db"`
}

func (exportRecordsDb *ExportRecordsDb) Set() { // set方法
exportRecordsDb.Db = Db
}

func (exportRecordsDb *ExportRecordsDb) GetExportRecordsExportRecords(id int) (m *model.ExportRecords, err error) {
m = new(model.ExportRecords)
has, err := exportRecordsDb.Db.Where("id =?", id).Get(m)
if err != nil {
return nil, logx.Error(err)
}
if has == false {
return nil, nil
}
return m, nil
}

func (exportRecordsDb *ExportRecordsDb) GetExportRecordsExportRecordsByMonth(year, month string) (m *model.ExportRecords, err error) {
m = new(model.ExportRecords)
has, err := exportRecordsDb.Db.Where("year =? and month =?", year, month).Get(m)
if err != nil {
return nil, logx.Error(err)
}
if has == false {
return nil, nil
}
return m, nil
}

func (exportRecordsDb *ExportRecordsDb) FindExportRecordsExportRecords() (*[]model.ExportRecords, error) {
var m []model.ExportRecords
if err := exportRecordsDb.Db.Desc("id").Find(&m); err != nil {
return nil, logx.Error(err)
}
return &m, nil
}

func (exportRecordsDb *ExportRecordsDb) ExportRecordsExportRecordsInsert(m *model.ExportRecords) (int, error) {
_, err := exportRecordsDb.Db.InsertOne(m)
if err != nil {
return 0, err
}
return m.Id, nil
}

func (exportRecordsDb *ExportRecordsDb) ExportRecordsExportRecordsInsertBySession(session *xorm.Session, m *model.ExportRecords) (int, error) {
_, err := session.InsertOne(m)
if err != nil {
return 0, err
}
return m.Id, nil
}

func (exportRecordsDb *ExportRecordsDb) ExportRecordsExportRecordsDelete(id interface{}) (int64, error) {
if reflect.TypeOf(id).Kind() == reflect.Slice {
return Db.In("id", id).Delete(model.ExportRecords{})
} else {
return Db.Where("id = ?", id).Delete(model.ExportRecords{})
}
}

func (exportRecordsDb *ExportRecordsDb) ExportRecordsExportRecordsUpdateBySession(session *xorm.Session, id interface{}, m *model.ExportRecords, forceColums ...string) (int64, error) {
var (
affected int64
err error
)
if forceColums != nil {
affected, err = session.Where("id=?", id).Cols(forceColums...).Update(m)
} else {
affected, err = session.Where("id=?", id).Update(m)
}
if err != nil {
return 0, err
}
return affected, nil
}

func (exportRecordsDb *ExportRecordsDb) ExportRecordsExportRecordsList(req md.ExportRecordsListReq) (m []model.ExportRecords, total int64, err error) {
sess := exportRecordsDb.Db.Desc("id")
if req.Kind != 0 {
sess.And("kind =?", req.Kind)
}
if req.StartDate != "" {
sess.And("create_at >=?", req.StartDate)
}
if req.EndDate != "" {
sess.And("create_at <=?", req.EndDate)
}
total, err = sess.Limit(req.Limit, (req.Page-1)*req.Limit).FindAndCount(&m)
if err != nil {
return
}
return
}

+ 9
- 0
app/db/db_order_list.go View File

@@ -96,6 +96,15 @@ func GetOrderListExport(eg *xorm.Engine, param map[string]string) (*[]model.Orde
if param["end_at"] != "" {
sess.And("create_at <= ?", param["end_at"])
}
if param["start_at_for_date"] != "" && param["start_at_for_date"] != "00010101" {
sess.And("date >= ?", param["start_at_for_date"])
}
if param["end_at_for_date"] != "" && param["end_at_for_date"] != "00010101" {
sess.And("date <= ?", param["end_at_for_date"])
}
if param["enterprise_id"] != "" && param["enterprise_id"] != "0" {
sess.And("enterprise_id = ?", param["enterprise_id"])
}
if param["enterprise_name"] != "" {
var enterprise []model.Enterprise
eg.Where("name like ?", "%"+param["enterprise_name"]+"%").Find(&enterprise)


+ 11
- 0
app/db/model/export_records.go View File

@@ -0,0 +1,11 @@
package model

type ExportRecords struct {
Id int `json:"id" xorm:"not null pk autoincr INT(11)"`
Name string `json:"name" xorm:"not null default '' comment('名称') VARCHAR(255)"`
DownloadPath string `json:"download_path" xorm:"not null default '' comment('下载地址') VARCHAR(255)"`
Kind int `json:"kind" xorm:"not null default 0 comment('类型(1:订单列表 2:退款申请表 3:预定统计表)') TINYINT(1)"`
ReqContent string `json:"req_content" xorm:"TEXT"`
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"`
}

+ 13
- 6
app/router/admin_router.go View File

@@ -147,6 +147,12 @@ func rOrder(r *gin.RouterGroup) {
r.POST("/makeRecord", orderHdl.MarkRecord) //制作记录
}

func rDataStatistics(r *gin.RouterGroup) {
r.POST("/list", hdl.DataStatisticsList) //列表
r.POST("/export", hdl.DataStatisticsExport) //导出
r.POST("/delete", hdl.DataStatisticsDelete) //删除
}

func rFinanceManage(r *gin.RouterGroup) {
r.POST("/list", orderHdl.OrderList) //用户订单
r.POST("/export", orderHdl.OrderExport) //用户订单导出
@@ -174,10 +180,11 @@ func AdminRoute(r *gin.RouterGroup) {
rCategory(r.Group("/category")) //商品类目
rGoods(r.Group("/goods")) //商品

rRole(r.Group("/role")) //权限管理
rSetCenter(r.Group("/setCenter")) //设置中心
rStaff(r.Group("/staff")) //员工管理
rGoodsPay(r.Group("/goodsPay")) //商品下单
rOrder(r.Group("/order")) //用户订单
rFinanceManage(r.Group("/financeManage")) //财务管理
rRole(r.Group("/role")) //权限管理
rSetCenter(r.Group("/setCenter")) //设置中心
rStaff(r.Group("/staff")) //员工管理
rGoodsPay(r.Group("/goodsPay")) //商品下单
rOrder(r.Group("/order")) //用户订单
rFinanceManage(r.Group("/financeManage")) //财务管理
rDataStatistics(r.Group("/dataStatistics")) //数据统计
}

+ 4
- 1
k8s/deployment-prd.yaml View File

@@ -50,7 +50,7 @@ spec:
# 主容器
- name: bakery
# 镜像地址(提前打包好并推送的镜像仓库)
image: 'registry.cn-shenzhen.aliyuncs.com/fnuoos-prd/bakery:1.0.0'
image: 'registry.cn-shenzhen.aliyuncs.com/fnuoos-prd/bakery:24043014'
ports:
- name: httpsupply4001
# 容器端口号(注意与golang web server启动的端口一致)
@@ -65,6 +65,9 @@ spec:
readOnly: true
# 挂载到容器的哪个路径
mountPath: /var/zyos
# 存储卷 用于存放前端代码
- name: bakery # 前面volumes声明的名称
mountPath: /data
imagePullPolicy: Always
# Nginx 容器
- name: container-nginx


BIN
View File


Loading…
Cancel
Save