This commit is contained in:
2025-07-07 20:11:59 +08:00
parent ab0fdbc447
commit 06e3aa2eb3
2009 changed files with 193082 additions and 0 deletions

View File

@ -0,0 +1,511 @@
// ==========================================================================
// GFast自动生成logic操作代码。
// 生成日期2024-04-02 18:03:23
// 生成路径: internal/app/system/logic/bus_weekly_security_report.go
// 生成人gfast
// desc:安全周期
// company:云南奇讯科技有限公司
// ==========================================================================
package logic
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
"github.com/tiger1103/gfast/v3/api/v1/common/coryCommon"
"github.com/tiger1103/gfast/v3/api/v1/system"
"github.com/tiger1103/gfast/v3/internal/app/system/consts"
"github.com/tiger1103/gfast/v3/internal/app/system/dao"
busQuestionSave "github.com/tiger1103/gfast/v3/internal/app/system/logic/busQuestionSave"
ct "github.com/tiger1103/gfast/v3/internal/app/system/logic/context"
"github.com/tiger1103/gfast/v3/internal/app/system/model"
"github.com/tiger1103/gfast/v3/internal/app/system/model/do"
"github.com/tiger1103/gfast/v3/internal/app/system/service"
"github.com/tiger1103/gfast/v3/library/liberr"
tool "github.com/tiger1103/gfast/v3/utility/coryUtils"
)
func init() {
service.RegisterBusWeeklySecurityReport(New())
}
func New() *sBusWeeklySecurityReport {
return &sBusWeeklySecurityReport{}
}
type sBusWeeklySecurityReport struct{}
func (s *sBusWeeklySecurityReport) List(ctx context.Context, req *system.BusWeeklySecurityReportSearchReq) (listRes *system.BusWeeklySecurityReportSearchRes, err error) {
listRes = new(system.BusWeeklySecurityReportSearchRes)
err = g.Try(ctx, func(ctx context.Context) {
m := dao.BusWeeklySecurityReport.Ctx(ctx).WithAll()
if req.ProjectId != "" {
m = m.Where(dao.BusWeeklySecurityReport.Columns().ProjectId+" = ?", gconv.Int64(req.ProjectId))
}
if req.ScopeDate != "" {
split := strings.Split(req.ScopeDate, ",")
m = m.Where("DATE_FORMAT(scope,'%Y-%m-%d') >=? AND DATE_FORMAT(scope,'%Y-%m-%d') <=?", split[0], split[1])
}
//if req.Scope != "" {
// m = m.Where(dao.BusWeeklySecurityReport.Columns().Scope+" = ?", req.Scope)
//}
//if req.ScopeEnd != "" {
// m = m.Where(dao.BusWeeklySecurityReport.Columns().ScopeEnd+" = ?", req.ScopeEnd)
//}
if len(req.DateRange) != 0 {
m = m.Where(dao.BusWeeklySecurityReport.Columns().CreatedAt+" >=? AND "+dao.BusWeeklySecurityReport.Columns().CreatedAt+" <=?", req.DateRange[0], req.DateRange[1])
}
listRes.Total, err = m.Count()
liberr.ErrIsNil(ctx, err, "获取总行数失败")
if req.PageNum == 0 {
req.PageNum = 1
}
listRes.CurrentPage = req.PageNum
if req.PageSize == 0 {
req.PageSize = consts.PageSize
}
order := "id desc"
if req.OrderBy != "" {
order = req.OrderBy
}
var res []*model.BusWeeklySecurityReportInfoRes
err = m.Fields(system.BusWeeklySecurityReportSearchRes{}).Page(req.PageNum, req.PageSize).Order(order).Scan(&res)
liberr.ErrIsNil(ctx, err, "获取数据失败")
listRes.List = make([]*model.BusWeeklySecurityReportListRes, len(res))
for k, v := range res {
ve := coryCommon.SelectByString(ctx, coryCommon.IsNumeric(v.CreateBy), v.CreateBy)
listRes.List[k] = &model.BusWeeklySecurityReportListRes{
Id: v.Id,
ProjectId: v.ProjectId,
ProjectName: v.ProjectName,
Week: v.Week,
Scope: v.Scope,
ScopeEnd: v.ScopeEnd,
Path: v.Path,
CreateBy: ve,
UpdateBy: v.UpdateBy,
CreatedAt: v.CreatedAt,
}
}
})
return
}
func (s *sBusWeeklySecurityReport) GetById(ctx context.Context, id int64) (res *model.BusWeeklySecurityReportInfoRes, err error) {
err = g.Try(ctx, func(ctx context.Context) {
err = dao.BusWeeklySecurityReport.Ctx(ctx).WithAll().Where(dao.BusWeeklySecurityReport.Columns().Id, id).Scan(&res)
// 获取创建人 更新人名称
by := coryCommon.New().CreateByOrUpdateBy(ctx, res)
infoRes := by.(model.BusWeeklySecurityReportInfoRes)
res = &infoRes
liberr.ErrIsNil(ctx, err, "获取信息失败")
})
return
}
func (s *sBusWeeklySecurityReport) Add(ctx context.Context, req *system.BusWeeklySecurityReportAddReq) (err error) {
err = g.Try(ctx, func(ctx context.Context) {
split := strings.Split(req.TimeRange, ",")
// 1、获取周期
weekFunc := WeekFunc(split[1])
// 2、需要插入的数据
report := do.BusWeeklySecurityReport{
ProjectId: req.ProjectId,
Week: weekFunc,
Scope: split[0],
ScopeEnd: split[1],
CreateBy: ct.New().GetLoginUser(ctx).Id,
}
// 3、自动生成数据
res, err := WeeklySecurityReportFunc(ctx, req)
liberr.ErrIsNil(ctx, err)
// 4、生成word返回路径
jsonData, err := WeeklySecurityReportHttp(ctx, res)
str, err := SelectData(ctx, jsonData, strconv.FormatInt(req.ProjectId, 10))
liberr.ErrIsNil(ctx, err)
if str == "" {
err = errors.New("添加失败")
liberr.ErrIsNil(ctx, err)
return
}
path := coryCommon.ResourcePublicToFunc(str, 1)
if path == "" {
err = errors.New("添加失败")
liberr.ErrIsNil(ctx, err)
return
}
report.Path = path
_, err = dao.BusWeeklySecurityReport.Ctx(ctx).Insert(report)
liberr.ErrIsNil(ctx, err, "添加失败")
})
return
}
func (s *sBusWeeklySecurityReport) Edit(ctx context.Context, req *system.BusWeeklySecurityReportEditReq) (err error) {
err = g.Try(ctx, func(ctx context.Context) {
_, err = dao.BusWeeklySecurityReport.Ctx(ctx).WherePri(req.Id).Update(do.BusWeeklySecurityReport{
ProjectId: req.ProjectId,
ProjectName: req.ProjectName,
Scope: req.Scope,
ScopeEnd: req.ScopeEnd,
Path: req.Path,
CreateBy: req.CreateBy,
UpdateBy: req.UpdateBy,
})
liberr.ErrIsNil(ctx, err, "修改失败")
})
return
}
func (s *sBusWeeklySecurityReport) Delete(ctx context.Context, ids []int64) (err error) {
err = g.Try(ctx, func(ctx context.Context) {
// 查询数据
array, err := dao.BusWeeklySecurityReport.Ctx(ctx).Fields("path").Where("id in (?)", ids).Array()
liberr.ErrIsNil(ctx, err)
// 删除数据
_, err = dao.BusWeeklySecurityReport.Ctx(ctx).Unscoped().Delete(dao.BusWeeklySecurityReport.Columns().Id+" in (?)", ids)
liberr.ErrIsNil(ctx, err)
// 删除文件
var p []string
for i := range array {
p = append(p, array[i].String())
}
coryCommon.BatchFile(p)
liberr.ErrIsNil(ctx, err, "删除失败")
})
return
}
func WeeklySecurityReportFunc(ctx context.Context, req *system.BusWeeklySecurityReportAddReq) (res *system.WeeklySecurityReportRes, err error) {
res = new(system.WeeklySecurityReportRes)
var entity []*system.WeeklySecurityReportEntity
err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
err = g.Try(ctx, func(ctx context.Context) {
te := strings.Split(req.TimeRange, ",")
////0、获取到所有正常的项目
//array, _ := dao.SysProject.Ctx(ctx).Where(dao.SysProject.Columns().Status, "0").Fields("id").Array()
var array []string
array = append(array, fmt.Sprintf("%d", req.ProjectId))
if len(array) > 0 {
for i := range array {
v2, _ := dao.SysProject.Ctx(ctx).WherePri(array).Fields("project_name").Value()
projectId := array[i]
reportEntity := system.WeeklySecurityReportEntity{
ProjectName: v2.String(),
}
pro, _ := strconv.ParseInt(projectId, 10, 64)
reportEntity.ProjectId = pro
reportEntity.Begin = te[0]
reportEntity.End = te[1]
/**
一、本周项目人员投入情况
*/
values, err := g.DB().Model("bus_attendance").Ctx(ctx).
Where("project_id", projectId).
WhereBetween("printing_date", te[0], te[1]).
Fields("openid").Array()
liberr.ErrIsNil(ctx, err)
var openids []string
if len(values) > 0 {
for i2 := range values {
openids = append(openids, values[i2].String())
}
}
if len(openids) > 0 {
v, err := dao.BusConstructionUser.Ctx(ctx).
Fields(`COUNT( CASE WHEN type_of_work NOT IN ( "9" ) THEN 0 END ) AS builders`).
Where(dao.BusConstructionUser.Columns().ProjectId).Where("openid in (?)", openids).Value()
liberr.ErrIsNil(ctx, err)
reportEntity.Builders = v.Int()
}
/**
二、本周项目人员投入情况
*/
v, err := g.DB().Model("sys_project_team_member").Ctx(ctx).
Fields("count(id) as attendance").
Where("project_id", projectId).WhereBetween("DATE_FORMAT(create_time,'%Y-%m-%d')", te[0], te[1]).Value()
liberr.ErrIsNil(ctx, err)
num := 0
parseInt, _ := strconv.ParseInt(projectId, 10, 64)
r, err := busQuestionSave.WeChatPdfWo(ctx, &system.WeChatPdfWoReq{ProjectId: parseInt})
for _, data := range r {
format := data.CreatedAt.Format("Y-m-d")
flag := tool.StringDateComparison(format, te[0], te[1])
if flag {
num = num + 1
}
}
reportEntity.Attendance = v.Int()
reportEntity.Education = num
/**
三、本周特种设备投入情况
*/
bt := "DATE_FORMAT(a.created_at,'%Y-%m-%d') BETWEEN '" + te[0] + "' and '" + te[1] + "'"
// exec, err := g.DB().Query(ctx, `SELECT
// a.machinery_name as machineName,
// a.machinery_number as machineType,
// (SELECT count(id) FROM bus_machinery_detail WHERE machinery_id = a.id and type = 2 and `+bt+`) as enter,
// (SELECT count(id) FROM bus_machinery_detail WHERE machinery_id = a.id and type = 1 and `+bt+`) as quit,
// (SELECT count(id) FROM bus_machinery_detail WHERE machinery_id = a.id and type = 2 ) as addUp
// FROM
// bus_machinery as a
// WHERE
// project_id = `+projectId+``)
var lsEntity []*system.LargeScaleTwoEntity
exec, err := g.DB().Query(ctx, generateQuery(projectId, te[0], te[1]))
err = exec.Structs(&lsEntity)
liberr.ErrIsNil(ctx, err)
if lsEntity != nil {
var ls []*system.LargeScaleEntity
for i2, datai2 := range lsEntity {
ls = append(ls, &system.LargeScaleEntity{
Num: i2 + 1,
//Machine: datai2.MachineName + "" + datai2.MachineType,
Machine: datai2.MachineName,
Numnber: datai2.Enter - datai2.Quit,
AddUp: datai2.AddUp,
})
}
reportEntity.LargeScaleList = ls
}
/**
四、本周安全检查记录
*/
query, err := g.DB().Query(ctx, `SELECT
a.created_at as time,
c.dict_label as riskGrade,
d.dict_label as problemDescription
FROM
bus_violation_record as a
LEFT JOIN bus_violation_level as b on b.id = a.level_id
LEFT JOIN sys_dict_data as c on c.dict_type = 'risx' and c.dict_value = b.risx
LEFT JOIN sys_dict_data as d on d.dict_type = 'tour_type' and d.dict_value = a.tour_type
WHERE
a.project_id = `+projectId+` and `+bt)
var skEntity []*system.SecurityCheckEntity
err = query.Structs(&skEntity)
liberr.ErrIsNil(ctx, err)
if skEntity != nil {
for i3 := range skEntity {
skEntity[i3].Num = i3 + 1
}
reportEntity.SecurityCheckList = skEntity
}
/**
五、本周安全整改情况
*/
row4or5 := `SELECT
a.inspection_result inspectionResult,
a.rectification_time as tiem,
a.status,
a.review_type
FROM
bus_hse_management as a
WHERE
a.project_id = ` + projectId + ` and ` + bt
result, err := g.DB().Query(ctx, row4or5+` and is_reply = 1 and status in ("2","3")`)
var agEntity []*system.AbarbeitungTwoEntity
err = result.Structs(&agEntity)
liberr.ErrIsNil(ctx, err)
if agEntity != nil {
var ag []*system.AbarbeitungEntity
for i2, datai2 := range agEntity {
abarbeitungEntity := system.AbarbeitungEntity{
Num: i2 + 1,
Tiem: datai2.Tiem,
InspectionResult: datai2.InspectionResult,
Condition: datai2.InspectionResult,
}
if datai2.Status == "1" {
abarbeitungEntity.Condition = "通知"
} else if datai2.Status == "2" {
abarbeitungEntity.Condition = "整改"
} else {
if datai2.ReviewType == "1" {
abarbeitungEntity.Condition = "复检通过"
} else {
abarbeitungEntity.Condition = "复检拒绝"
}
}
ag = append(ag, &abarbeitungEntity)
}
reportEntity.AbarbeitungList = ag
}
/**
六、本周可视化
*/
var ig []*system.ImgEntity
//站班会
var igEntity *system.ImgEntity
err = g.DB().Model("sys_project_team_squad").Ctx(ctx).
Fields("picture as path,content as text").
Where("project_id", projectId).
WhereBetween("created_at", te[0], te[1]).OrderDesc("id").Limit(1).Scan(&igEntity)
liberr.ErrIsNil(ctx, err)
if igEntity != nil {
trim := strings.Trim(igEntity.Path, "")
if trim != "" {
split := strings.Split(trim, ",")
slash := filepath.ToSlash(split[0])
if strings.Contains(slash, "/wxfile/") {
split[0] = strings.Replace(slash, "/wxfile/", coryCommon.GetCWD()+"/resource/public/", 1)
} else {
split[0] = strings.Replace(slash, "/file/", coryCommon.GetCWD()+"/resource/public/", 1)
}
ig = append(ig, &system.ImgEntity{
Path: split[0],
Text: igEntity.Text,
})
reportEntity.ImgList = ig
}
}
//hse安全工单
sql := `SELECT
a.inspection_result as text,
b.path
FROM
bus_hse_management AS a
LEFT JOIN bus_hse_management_path as b on b.ticket_id = a.id
WHERE
a.project_id = ` + projectId + ` and ` + bt + ` and is_reply = '2' and path is not null
GROUP BY inspection_result
`
var gdEntity []*system.ImgEntity
resultSix, errSix := g.DB().Query(ctx, sql)
err = resultSix.Structs(&gdEntity)
liberr.ErrIsNil(ctx, errSix)
if gdEntity != nil {
for i2 := range gdEntity {
slash := filepath.ToSlash(gdEntity[i2].Path)
if strings.Contains(slash, "/wxfile/") {
gdEntity[i2].Path = strings.Replace(slash, "/wxfile/", coryCommon.GetCWD()+"/resource/public/", 1)
} else {
gdEntity[i2].Path = strings.Replace(slash, "/file/", coryCommon.GetCWD()+"/resource/public/", 1)
}
}
ig = append(ig, gdEntity[0])
ig = append(ig, gdEntity[len(gdEntity)-1])
reportEntity.ImgList = ig
}
// g.DB().Model("bus_construction_user_departure").Ctx(ctx).Wher
// r2, err := g.DB().Query(ctx, `SELECT
// b.path
// FROM
// bus_hse_management as a
// LEFT JOIN bus_hse_management_path as b on b.ticket_id = a.id
// WHERE
// a.project_id = `+projectId+`and`+bt+`ORDER BY RAND() LIMIT 1`)
// r2.Structs()
entity = append(entity, &reportEntity)
}
res.WeeklySecurityReport = entity
liberr.ErrIsNil(ctx, err)
}
})
return err
})
return
}
func WeeklySecurityReportHttp(ctx context.Context, weekly *system.WeeklySecurityReportRes) (allString string, err error) {
uri := "http://" + coryCommon.Global + ":8899/airlineserver/" + "word/wordTemplateExport"
//uri := "127.0.0.1:9992/word/wordTemplateExport"
weekly.FilePath = coryCommon.ResourcePublicToFunc(filepath.ToSlash("/"+coryCommon.Ynr(coryCommon.Helmet)), 2)
// weekly.FilePath = "/project/zmkg/resource/public/upload_file/2024-04-03/"
airJson, err := json.Marshal(weekly)
response, err := g.Client().Post(ctx, uri, airJson)
allString = response.ReadAllString()
return
}
func WeekFunc(timeStr string) string {
// 解析字符串时间为时间对象
t, _ := time.Parse("2006-01-02", timeStr)
// 获取ISO周数
_, week := t.ISOWeek()
//return fmt.Sprintf("%s 是第 %d 周\n", timeStr, week)
return fmt.Sprintf("第 %d 周\n", week)
}
// 定义结构体来解析JSON
type Response struct {
Success bool `json:"success"`
Code int `json:"code"`
Message string `json:"message"`
Data map[string]interface{} `json:"data"`
}
func SelectData(ctx context.Context, jsonData string, projectId string) (str string, err error) {
err = g.Try(ctx, func(ctx context.Context) {
// 解析JSON数据
var response Response
err := json.Unmarshal([]byte(jsonData), &response)
if err != nil {
fmt.Println("解析JSON失败:", err)
return
}
// 提取路径值
path, ok := response.Data[projectId].(string)
if !ok {
err = errors.New("路径值无效")
return
}
str = filepath.ToSlash(path)
})
return
}
func generateQuery(projectId, startDate, endDate string) string {
return fmt.Sprintf(`SELECT
a.machinery_name AS machineName,
SUM(
(SELECT
count(id)
FROM
bus_machinery_detail
WHERE
machinery_id = a.id
AND TYPE = 2
AND DATE_FORMAT(a.created_at, '%%Y-%%m-%%d') BETWEEN '%s'
AND '%s')
) AS enter,
SUM(
(SELECT
count(id)
FROM
bus_machinery_detail
WHERE
machinery_id = a.id
AND TYPE = 1
AND DATE_FORMAT(a.created_at, '%%Y-%%m-%%d') BETWEEN '%s'
AND '%s')
) AS quit,
SUM(
(SELECT
count(id)
FROM
bus_machinery_detail
WHERE
machinery_id = a.id
AND TYPE = 2)
) AS addUp
FROM
bus_machinery AS a
WHERE
project_id = %s
GROUP BY
a.machinery_name;`, startDate, endDate, startDate, endDate, projectId)
}