123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604 |
- package service
- import (
- "cold-logistics/app/admin/model"
- "cold-logistics/app/admin/service/dto"
- "cold-logistics/common/actions"
- cDto "cold-logistics/common/dto"
- "cold-logistics/common/global"
- model2 "cold-logistics/common/model"
- "cold-logistics/common/nats/nats_server"
- "errors"
- "fmt"
- "gogs.baozhida.cn/zoie/OAuth-core/service"
- "gorm.io/gorm"
- "sort"
- "time"
- )
- type WaybillTask struct {
- service.Service
- }
- func WaybillTaskTimeScopes(startTime, endTime string) func(db *gorm.DB) *gorm.DB {
- return func(db *gorm.DB) *gorm.DB {
- if len(startTime) == 0 && len(endTime) == 0 {
- return db
- }
- return db.Where("(start_time between ? and ?) or (end_time between ? and ?)",
- startTime, endTime, startTime, endTime)
- }
- }
- func WaybillTaskIdsScopes(ids []int) func(db *gorm.DB) *gorm.DB {
- return func(db *gorm.DB) *gorm.DB {
- if len(ids) == 0 {
- return db
- }
- return db.Where("id in (?)", ids)
- }
- }
- // GetPage 获取WaybillTask列表
- func (e *WaybillTask) GetPage(c *dto.WaybillTaskGetPageReq, list *[]model.WaybillTask, count *int64) error {
- var err error
- var data model.WaybillTask
- var waybill model.Waybill
- err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return errors.New("获取运单信息失败")
- }
- err = e.Orm.Model(&data).
- Scopes(
- cDto.MakeCondition(c.GetNeedSearch()),
- ).
- Preload("Warehouse").Preload("Car").Preload("CoolerBox").
- Find(list).Limit(-1).Offset(-1).
- Count(count).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.GetFailedErr
- }
- // 获取公司秘钥
- var company model.SysDept
- company, err = model.GetCompanyById(waybill.DeptId)
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return model.GetCompanyKeyErr
- }
- for i := 0; i < len(*list); i++ {
- // 获取传感器信息
- deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey((*list)[i].Sn, company.ColdKey)
- (*list)[i].DeviceSensorList = deviceSensorList
- }
- return nil
- }
- // GetPage 获取WaybillTask列表
- func (e *WaybillTask) GetDataPage(c *dto.WaybillTaskGetDataPageReq) (list []nats_server.DeviceData_R, count int64, err error) {
- var waybill model.Waybill
- err = e.Orm.Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = errors.New("获取运单信息错误!")
- return
- }
- var task model.WaybillTask
- err = e.Orm.Where("id = ? and waybill_no = ?", c.TaskId, c.WaybillNo).First(&task).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = errors.New("获取运单信息错误!")
- return
- }
- // 获取最后一个任务id
- var lastWaybillTask model.WaybillTask
- err = e.Orm.Model(&lastWaybillTask).Where("waybill_no = ?", c.WaybillNo).Last(&lastWaybillTask).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = errors.New("获取运单信息错误!")
- return
- }
- var afterStartTime bool
- var beforeEndTime bool
- if len(c.StartTime) > 0 {
- var st time.Time
- st, err = time.ParseInLocation("2006-01-02 15:04:05", c.StartTime, time.Local)
- if err != nil {
- err = errors.New("解析时间字符串出错!")
- return
- }
- fmt.Println("st", st)
- fmt.Println("task.StartTime", task.StartTime.Local())
- if task.StartTime.Local().After(st) || st.Truncate(time.Second).Equal(task.StartTime.Local().Truncate(time.Second)) {
- c.StartTime = task.StartTime.String()
- } else {
- afterStartTime = true
- }
- } else {
- c.StartTime = task.StartTime.String()
- }
- if len(c.EndTime) > 0 {
- var et time.Time
- et, err = time.ParseInLocation("2006-01-02 15:04:05", c.EndTime, time.Local)
- if err != nil {
- err = errors.New("解析时间字符串出错!")
- return
- }
- fmt.Println("et", et)
- fmt.Println("task.EndTime", task.EndTime.Local())
- if et.After(task.EndTime.Local()) || et.Truncate(time.Second).Equal(task.EndTime.Local().Truncate(time.Second)) {
- c.EndTime = task.EndTime.String()
- } else {
- beforeEndTime = true
- }
- } else {
- c.EndTime = task.EndTime.String()
- }
- T_snid := ""
- for _, id := range c.T_ids {
- T_snid += fmt.Sprintf("%s,%d|", task.Sn, id)
- }
- list, count, err = nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, c.StartTime, c.EndTime, 0, 9999)
- sort.Slice(list, func(i, j int) bool {
- return list[i].T_time < list[j].T_time
- })
- firstMap := map[int]nats_server.DeviceData_R{}
- lastMap := map[int]nats_server.DeviceData_R{}
- if count > 0 {
- for _, v := range c.T_ids {
- for i := 0; i < len(list); i++ {
- if afterStartTime {
- break
- }
- if v == list[i].T_id {
- if list[i].T_time != task.StartTime.String() {
- data := list[len(list)-1-i]
- data.T_time = task.StartTime.String()
- firstMap[v] = data
- count += 1
- }
- break
- }
- }
- for i := len(list) - 1; i >= 0; i-- {
- if beforeEndTime {
- break
- }
- if v == list[i].T_id {
- if list[i].T_time != task.EndTime.String() && !task.EndTime.Local().IsZero() {
- data := list[len(list)-1-i]
- data.T_time = task.EndTime.String()
- lastMap[v] = data
- count += 1
- }
- break
- }
- }
- }
- }
- for _, data := range firstMap {
- list = append(list, data)
- }
- for _, data := range lastMap {
- list = append(list, data)
- }
- sort.Slice(list, func(i, j int) bool {
- // 先按 T_time 字段排序,如果 T_time 相同则按 T_name 字段排序
- if list[i].T_time == list[j].T_time {
- return list[i].T_name < list[j].T_name
- }
- return list[i].T_time > list[j].T_time
- })
- // 计算总页数
- totalPages := (int(count) + c.PageSize - 1) / c.PageSize
- // 如果n超出范围,返回错误
- if c.Page > totalPages {
- return []nats_server.DeviceData_R{}, count, err
- }
- if c.Page < 1 {
- c.Page = 1
- }
- // 计算当前页的数据
- start := (c.Page - 1) * c.PageSize
- end := start + c.PageSize
- if end > int(count) {
- end = int(count)
- }
- currentPage := list[start:end]
- return currentPage, count, err
- }
- func (e *WaybillTask) GetPrintDataPage(c *dto.WaybillTaskGetDataPageReq) (list []nats_server.DeviceData_R, count int64, err error) {
- var waybill model.Waybill
- err = e.Orm.Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = errors.New("获取运单信息错误!")
- return
- }
- var task model.WaybillTask
- err = e.Orm.Where("id = ? and waybill_no = ?", c.TaskId, c.WaybillNo).First(&task).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = errors.New("获取运单信息错误!")
- return
- }
- // 获取最后一个任务id
- var lastWaybillTask model.WaybillTask
- err = e.Orm.Model(&lastWaybillTask).Where("waybill_no = ?", c.WaybillNo).Last(&lastWaybillTask).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = errors.New("获取运单信息错误!")
- return
- }
- var afterStartTime bool
- var beforeEndTime bool
- if len(c.StartTime) > 0 {
- var st time.Time
- st, err = time.ParseInLocation("2006-01-02 15:04:05", c.StartTime, time.Local)
- if err != nil {
- err = errors.New("解析时间字符串出错!")
- return
- }
- fmt.Println("st", st)
- fmt.Println("task.StartTime", task.StartTime.Local())
- if task.StartTime.Local().After(st) || st.Truncate(time.Second).Equal(task.StartTime.Local().Truncate(time.Second)) {
- c.StartTime = task.StartTime.String()
- } else {
- afterStartTime = true
- }
- } else {
- c.StartTime = task.StartTime.String()
- }
- if len(c.EndTime) > 0 {
- var et time.Time
- et, err = time.ParseInLocation("2006-01-02 15:04:05", c.EndTime, time.Local)
- if err != nil {
- err = errors.New("解析时间字符串出错!")
- return
- }
- fmt.Println("et", et)
- fmt.Println("task.EndTime", task.EndTime.Local())
- if et.After(task.EndTime.Local()) || et.Truncate(time.Second).Equal(task.EndTime.Local().Truncate(time.Second)) {
- c.EndTime = task.EndTime.String()
- } else {
- beforeEndTime = true
- }
- } else {
- c.EndTime = task.EndTime.String()
- }
- T_snid := ""
- for _, id := range c.T_ids {
- T_snid += fmt.Sprintf("%s,%d|", task.Sn, id)
- }
- list, count, err = nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, c.StartTime, c.EndTime, 0, 9999)
- sort.Slice(list, func(i, j int) bool {
- return list[i].T_time < list[j].T_time
- })
- firstMap := map[int]nats_server.DeviceData_R{}
- lastMap := map[int]nats_server.DeviceData_R{}
- if count > 0 {
- for _, v := range c.T_ids {
- for i := 0; i < len(list); i++ {
- if afterStartTime {
- break
- }
- if v == list[i].T_id {
- if list[i].T_time != task.StartTime.String() {
- data := list[len(list)-1-i]
- data.T_time = task.StartTime.String()
- firstMap[v] = data
- count += 1
- }
- break
- }
- }
- for i := len(list) - 1; i >= 0; i-- {
- if beforeEndTime {
- break
- }
- if v == list[i].T_id {
- if list[i].T_time != task.EndTime.String() && !task.EndTime.Local().IsZero() {
- data := list[len(list)-1-i]
- data.T_time = task.EndTime.String()
- lastMap[v] = data
- count += 1
- }
- break
- }
- }
- }
- }
- for _, data := range firstMap {
- list = append(list, data)
- }
- for _, data := range lastMap {
- list = append(list, data)
- }
- sort.Slice(list, func(i, j int) bool {
- // 先按 T_time 字段排序,如果 T_time 相同则按 T_name 字段排序
- if list[i].T_time == list[j].T_time {
- return list[i].T_name < list[j].T_name
- }
- return list[i].T_time > list[j].T_time
- })
- // 计算总页数
- totalPages := (int(count) + c.PageSize - 1) / c.PageSize
- // 如果n超出范围,返回错误
- if c.Page > totalPages {
- return []nats_server.DeviceData_R{}, count, err
- }
- if c.Page < 1 {
- c.Page = 1
- }
- // 计算当前页的数据
- start := (c.Page - 1) * c.PageSize
- end := start + c.PageSize
- if end > int(count) {
- end = int(count)
- }
- currentPage := list[start:end]
- return currentPage, count, err
- }
- func (e *WaybillTask) GetNewestDataPage(c *dto.WaybillTaskGetNewestDataPageReq) (data nats_server.DeviceData_R, err error) {
- var waybill model.Waybill
- err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = errors.New("获取运单信息错误!")
- return
- }
- // 获取公司秘钥
- var company model.SysDept
- company, err = model.GetCompanyById(waybill.DeptId)
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = model.GetCompanyKeyErr
- return
- }
- var taskList []model.WaybillTask
- err = e.Orm.Where("waybill_no = ?", c.WaybillNo).Order("id desc").Find(&taskList).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- err = errors.New("获取运单信息任务失败!")
- return
- }
- if len(taskList) == 0 {
- err = errors.New("暂无温湿度记录信息!")
- return
- }
- var listAll []nats_server.DeviceData_R
- for _, task := range taskList {
- deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(task.Sn, company.ColdKey)
- if len(deviceSensorList) == 0 {
- continue
- }
- T_snid := fmt.Sprintf("%s,%d|", deviceSensorList[0].T_sn, deviceSensorList[0].T_id)
- if len(task.EndTime.String()) == 0 {
- task.EndTime = model2.Time(time.Now())
- }
- // 获取传感器信息
- list, _, _ := nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, task.StartTime.String(), task.EndTime.String(), 0, 9999)
- if len(list) > 0 {
- listAll = append(listAll, list...)
- break
- }
- }
- if len(listAll) > 0 {
- sort.Slice(listAll, func(i, j int) bool {
- return listAll[i].T_time > listAll[j].T_time
- })
- data = listAll[0]
- return
- }
- err = errors.New("暂无温湿度记录信息!")
- return
- }
- func (e *WaybillTask) GetLocus(c *dto.WaybillGetLocusReq) ([]nats_server.DeviceData_R2, error) {
- var err error
- var data model.WaybillTask
- var waybill model.Waybill
- var taskList []model.WaybillTask
- locusList := make([]nats_server.DeviceData_R2, 0)
- err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return locusList, errors.New("获取运单信息失败")
- }
- // 获取公司秘钥
- var company model.SysDept
- company, err = model.GetCompanyById(waybill.DeptId)
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return locusList, model.GetCompanyKeyErr
- }
- err = e.Orm.Model(&data).
- Scopes(
- cDto.MakeCondition(c.GetNeedSearch()),
- ).Where("car_id > 0 or cooler_box_id > 0 ").
- Find(&taskList).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return locusList, global.GetFailedErr
- }
- for i := 0; i < len(taskList); i++ {
- // 获取传感器信息
- deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(taskList[i].Sn, company.ColdKey)
- if len(deviceSensorList) > 0 {
- T_snid := fmt.Sprintf("%s,%d|", taskList[i].Sn, deviceSensorList[0].T_id)
- dataList, _, err := nats_server.Cold_ReadDeviceDataListBy_T_snidForLocus(T_snid, taskList[i].StartTime.String(), taskList[i].EndTime.String(), 0, 9999)
- if err != nil {
- e.Log.Errorf("nats 获取轨迹信息失败: %s", err)
- return locusList, global.GetFailedErr
- }
- // 倒序
- sort.Slice(dataList, func(i, j int) bool {
- if dataList[i].T_time < dataList[j].T_time {
- return true
- }
- return false
- })
- locusList = append(locusList, dataList...)
- }
- }
- return locusList, nil
- }
- // Update 修改Waybill对象
- func (e *WaybillTask) Update(c *dto.WaybillTaskUpdateReq, p *actions.DataPermission) error {
- var err error
- tx := e.Orm.Begin()
- defer func() {
- if err != nil {
- tx.Rollback()
- } else {
- tx.Commit()
- }
- }()
- for _, task := range c.WaybillTaskList {
- var waybillTaskModel = model.WaybillTask{}
- // 查询运单是否存在
- err = e.Orm.Scopes(actions.Permission(waybillTaskModel.TableName(), p)).
- First(&waybillTaskModel, task.Id).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return global.UpdateNotFoundOrNoPermissionErr
- }
- return global.UpdateFailedErr
- }
- oldStartTime := waybillTaskModel.StartTime
- oldEndTime := waybillTaskModel.EndTime
- // 修改运单物流时间
- if waybillTaskModel.StartTime != task.StartTime {
- var waybillLogistics = model.WaybillLogistics{}
- // 查询运单是否存在
- err = e.Orm.Scopes(actions.Permission(waybillLogistics.TableName(), p)).
- Where("created_at = ?", oldStartTime).First(&waybillLogistics).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return global.UpdateNotFoundOrNoPermissionErr
- }
- return global.UpdateFailedErr
- }
- waybillLogistics.CreatedAt = task.StartTime
- err = tx.Save(&waybillLogistics).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.UpdateFailedErr
- }
- }
- // 修改运单物流时间
- if waybillTaskModel.EndTime != task.EndTime {
- var waybillLogistics = model.WaybillLogistics{}
- // 查询运单是否存在
- err = e.Orm.Scopes(actions.Permission(waybillLogistics.TableName(), p)).
- Where("created_at = ? and status != ?", oldEndTime, model.WaybillStatusReceipt).Last(&waybillLogistics).Error
- if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
- e.Log.Errorf("db error: %s", err)
- return global.UpdateFailedErr
- }
- if waybillLogistics.Id > 0 {
- waybillLogistics.CreatedAt = task.EndTime
- err = tx.Save(&waybillLogistics).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.UpdateFailedErr
- }
- }
- }
- // 修改运单物流时间
- if waybillTaskModel.EndTime != task.EndTime {
- var waybillLogistics = model.WaybillLogistics{}
- // 查询运单是否存在
- err = e.Orm.Scopes(actions.Permission(waybillLogistics.TableName(), p)).
- Where("created_at = ? and status = ?", oldEndTime, model.WaybillStatusReceipt).Last(&waybillLogistics).Error
- if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
- e.Log.Errorf("db error: %s", err)
- return global.UpdateFailedErr
- }
- if waybillLogistics.Id > 0 {
- waybillLogistics.CreatedAt = task.EndTime
- err = tx.Save(&waybillLogistics).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.UpdateFailedErr
- }
- // 修改运单签收时间
- var waybillModel = model.Waybill{}
- // 查询运单是否存在
- err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
- Where("waybill_no = ?", waybillLogistics.WaybillNo).
- First(&waybillModel).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return errors.New(fmt.Sprintf("运单号%s不存在", waybillLogistics.WaybillNo))
- }
- return errors.New(fmt.Sprintf("运单号%s查询失败", waybillLogistics.WaybillNo))
- }
- waybillModel.ReceiptTime = task.StartTime
- err = tx.Save(&waybillModel).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return errors.New(fmt.Sprintf("保存运单信息失败:%s", err))
- }
- }
- }
- waybillTaskModel.StartTime = task.StartTime
- waybillTaskModel.EndTime = task.EndTime
- waybillTaskModel.UpdateBy = c.UpdateBy
- err = tx.Save(&waybillTaskModel).Error
- if err != nil {
- e.Log.Errorf("db error: %s", err)
- return global.UpdateFailedErr
- }
- }
- return nil
- }
|