waybill_task.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. package service
  2. import (
  3. "cold-logistics/app/admin/model"
  4. "cold-logistics/app/admin/service/dto"
  5. "cold-logistics/common/actions"
  6. cDto "cold-logistics/common/dto"
  7. "cold-logistics/common/global"
  8. model2 "cold-logistics/common/model"
  9. "cold-logistics/common/nats/nats_server"
  10. "errors"
  11. "fmt"
  12. "gogs.baozhida.cn/zoie/OAuth-core/service"
  13. "gorm.io/gorm"
  14. "sort"
  15. "time"
  16. )
  17. type WaybillTask struct {
  18. service.Service
  19. }
  20. func WaybillTaskTimeScopes(startTime, endTime string) func(db *gorm.DB) *gorm.DB {
  21. return func(db *gorm.DB) *gorm.DB {
  22. if len(startTime) == 0 && len(endTime) == 0 {
  23. return db
  24. }
  25. return db.Where("(start_time between ? and ?) or (end_time between ? and ?)",
  26. startTime, endTime, startTime, endTime)
  27. }
  28. }
  29. func WaybillTaskIdsScopes(ids []int) func(db *gorm.DB) *gorm.DB {
  30. return func(db *gorm.DB) *gorm.DB {
  31. if len(ids) == 0 {
  32. return db
  33. }
  34. return db.Where("id in (?)", ids)
  35. }
  36. }
  37. // GetPage 获取WaybillTask列表
  38. func (e *WaybillTask) GetPage(c *dto.WaybillTaskGetPageReq, list *[]model.WaybillTask, count *int64) error {
  39. var err error
  40. var data model.WaybillTask
  41. var waybill model.Waybill
  42. err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
  43. if err != nil {
  44. e.Log.Errorf("db error: %s", err)
  45. return errors.New("获取运单信息失败")
  46. }
  47. err = e.Orm.Model(&data).
  48. Scopes(
  49. cDto.MakeCondition(c.GetNeedSearch()),
  50. ).
  51. Preload("Warehouse").Preload("Car").Preload("CoolerBox").
  52. Find(list).Limit(-1).Offset(-1).
  53. Count(count).Error
  54. if err != nil {
  55. e.Log.Errorf("db error: %s", err)
  56. return global.GetFailedErr
  57. }
  58. // 获取公司秘钥
  59. var company model.SysDept
  60. company, err = model.GetCompanyById(waybill.DeptId)
  61. if err != nil {
  62. e.Log.Errorf("db error: %s", err)
  63. return model.GetCompanyKeyErr
  64. }
  65. for i := 0; i < len(*list); i++ {
  66. // 获取传感器信息
  67. deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey((*list)[i].Sn, company.ColdKey)
  68. (*list)[i].DeviceSensorList = deviceSensorList
  69. }
  70. return nil
  71. }
  72. // GetPage 获取WaybillTask列表
  73. func (e *WaybillTask) GetDataPage(c *dto.WaybillTaskGetDataPageReq) (list []nats_server.DeviceData_R, count int64, err error) {
  74. var waybill model.Waybill
  75. err = e.Orm.Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
  76. if err != nil {
  77. e.Log.Errorf("db error: %s", err)
  78. err = errors.New("获取运单信息错误!")
  79. return
  80. }
  81. var task model.WaybillTask
  82. err = e.Orm.Where("id = ? and waybill_no = ?", c.TaskId, c.WaybillNo).First(&task).Error
  83. if err != nil {
  84. e.Log.Errorf("db error: %s", err)
  85. err = errors.New("获取运单信息错误!")
  86. return
  87. }
  88. // 获取最后一个任务id
  89. var lastWaybillTask model.WaybillTask
  90. err = e.Orm.Model(&lastWaybillTask).Where("waybill_no = ?", c.WaybillNo).Last(&lastWaybillTask).Error
  91. if err != nil {
  92. e.Log.Errorf("db error: %s", err)
  93. err = errors.New("获取运单信息错误!")
  94. return
  95. }
  96. var afterStartTime bool
  97. var beforeEndTime bool
  98. if len(c.StartTime) > 0 {
  99. var st time.Time
  100. st, err = time.ParseInLocation("2006-01-02 15:04:05", c.StartTime, time.Local)
  101. if err != nil {
  102. err = errors.New("解析时间字符串出错!")
  103. return
  104. }
  105. fmt.Println("st", st)
  106. fmt.Println("task.StartTime", task.StartTime.Local())
  107. if task.StartTime.Local().After(st) || st.Truncate(time.Second).Equal(task.StartTime.Local().Truncate(time.Second)) {
  108. c.StartTime = task.StartTime.String()
  109. } else {
  110. afterStartTime = true
  111. }
  112. } else {
  113. c.StartTime = task.StartTime.String()
  114. }
  115. if len(c.EndTime) > 0 {
  116. var et time.Time
  117. et, err = time.ParseInLocation("2006-01-02 15:04:05", c.EndTime, time.Local)
  118. if err != nil {
  119. err = errors.New("解析时间字符串出错!")
  120. return
  121. }
  122. fmt.Println("et", et)
  123. fmt.Println("task.EndTime", task.EndTime.Local())
  124. if et.After(task.EndTime.Local()) || et.Truncate(time.Second).Equal(task.EndTime.Local().Truncate(time.Second)) {
  125. c.EndTime = task.EndTime.String()
  126. } else {
  127. beforeEndTime = true
  128. }
  129. } else {
  130. c.EndTime = task.EndTime.String()
  131. }
  132. T_snid := ""
  133. for _, id := range c.T_ids {
  134. T_snid += fmt.Sprintf("%s,%d|", task.Sn, id)
  135. }
  136. list, count, err = nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, c.StartTime, c.EndTime, 0, 9999)
  137. sort.Slice(list, func(i, j int) bool {
  138. return list[i].T_time < list[j].T_time
  139. })
  140. firstMap := map[int]nats_server.DeviceData_R{}
  141. lastMap := map[int]nats_server.DeviceData_R{}
  142. if count > 0 {
  143. for _, v := range c.T_ids {
  144. for i := 0; i < len(list); i++ {
  145. if afterStartTime {
  146. break
  147. }
  148. if v == list[i].T_id {
  149. if list[i].T_time != task.StartTime.String() {
  150. data := list[len(list)-1-i]
  151. data.T_time = task.StartTime.String()
  152. firstMap[v] = data
  153. count += 1
  154. }
  155. break
  156. }
  157. }
  158. for i := len(list) - 1; i >= 0; i-- {
  159. if beforeEndTime {
  160. break
  161. }
  162. if v == list[i].T_id {
  163. if list[i].T_time != task.EndTime.String() && !task.EndTime.Local().IsZero() {
  164. data := list[len(list)-1-i]
  165. data.T_time = task.EndTime.String()
  166. lastMap[v] = data
  167. count += 1
  168. }
  169. break
  170. }
  171. }
  172. }
  173. }
  174. for _, data := range firstMap {
  175. list = append(list, data)
  176. }
  177. for _, data := range lastMap {
  178. list = append(list, data)
  179. }
  180. sort.Slice(list, func(i, j int) bool {
  181. // 先按 T_time 字段排序,如果 T_time 相同则按 T_name 字段排序
  182. if list[i].T_time == list[j].T_time {
  183. return list[i].T_name < list[j].T_name
  184. }
  185. return list[i].T_time > list[j].T_time
  186. })
  187. // 计算总页数
  188. totalPages := (int(count) + c.PageSize - 1) / c.PageSize
  189. // 如果n超出范围,返回错误
  190. if c.Page > totalPages {
  191. return []nats_server.DeviceData_R{}, count, err
  192. }
  193. if c.Page < 1 {
  194. c.Page = 1
  195. }
  196. // 计算当前页的数据
  197. start := (c.Page - 1) * c.PageSize
  198. end := start + c.PageSize
  199. if end > int(count) {
  200. end = int(count)
  201. }
  202. currentPage := list[start:end]
  203. return currentPage, count, err
  204. }
  205. func (e *WaybillTask) GetPrintDataPage(c *dto.WaybillTaskGetDataPageReq) (list []nats_server.DeviceData_R, count int64, err error) {
  206. var waybill model.Waybill
  207. err = e.Orm.Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
  208. if err != nil {
  209. e.Log.Errorf("db error: %s", err)
  210. err = errors.New("获取运单信息错误!")
  211. return
  212. }
  213. var task model.WaybillTask
  214. err = e.Orm.Where("id = ? and waybill_no = ?", c.TaskId, c.WaybillNo).First(&task).Error
  215. if err != nil {
  216. e.Log.Errorf("db error: %s", err)
  217. err = errors.New("获取运单信息错误!")
  218. return
  219. }
  220. // 获取最后一个任务id
  221. var lastWaybillTask model.WaybillTask
  222. err = e.Orm.Model(&lastWaybillTask).Where("waybill_no = ?", c.WaybillNo).Last(&lastWaybillTask).Error
  223. if err != nil {
  224. e.Log.Errorf("db error: %s", err)
  225. err = errors.New("获取运单信息错误!")
  226. return
  227. }
  228. var afterStartTime bool
  229. var beforeEndTime bool
  230. if len(c.StartTime) > 0 {
  231. var st time.Time
  232. st, err = time.ParseInLocation("2006-01-02 15:04:05", c.StartTime, time.Local)
  233. if err != nil {
  234. err = errors.New("解析时间字符串出错!")
  235. return
  236. }
  237. fmt.Println("st", st)
  238. fmt.Println("task.StartTime", task.StartTime.Local())
  239. if task.StartTime.Local().After(st) || st.Truncate(time.Second).Equal(task.StartTime.Local().Truncate(time.Second)) {
  240. c.StartTime = task.StartTime.String()
  241. } else {
  242. afterStartTime = true
  243. }
  244. } else {
  245. c.StartTime = task.StartTime.String()
  246. }
  247. if len(c.EndTime) > 0 {
  248. var et time.Time
  249. et, err = time.ParseInLocation("2006-01-02 15:04:05", c.EndTime, time.Local)
  250. if err != nil {
  251. err = errors.New("解析时间字符串出错!")
  252. return
  253. }
  254. fmt.Println("et", et)
  255. fmt.Println("task.EndTime", task.EndTime.Local())
  256. if et.After(task.EndTime.Local()) || et.Truncate(time.Second).Equal(task.EndTime.Local().Truncate(time.Second)) {
  257. c.EndTime = task.EndTime.String()
  258. } else {
  259. beforeEndTime = true
  260. }
  261. } else {
  262. c.EndTime = task.EndTime.String()
  263. }
  264. T_snid := ""
  265. for _, id := range c.T_ids {
  266. T_snid += fmt.Sprintf("%s,%d|", task.Sn, id)
  267. }
  268. list, count, err = nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, c.StartTime, c.EndTime, 0, 9999)
  269. sort.Slice(list, func(i, j int) bool {
  270. return list[i].T_time < list[j].T_time
  271. })
  272. firstMap := map[int]nats_server.DeviceData_R{}
  273. lastMap := map[int]nats_server.DeviceData_R{}
  274. if count > 0 {
  275. for _, v := range c.T_ids {
  276. for i := 0; i < len(list); i++ {
  277. if afterStartTime {
  278. break
  279. }
  280. if v == list[i].T_id {
  281. if list[i].T_time != task.StartTime.String() {
  282. data := list[len(list)-1-i]
  283. data.T_time = task.StartTime.String()
  284. firstMap[v] = data
  285. count += 1
  286. }
  287. break
  288. }
  289. }
  290. for i := len(list) - 1; i >= 0; i-- {
  291. if beforeEndTime {
  292. break
  293. }
  294. if v == list[i].T_id {
  295. if list[i].T_time != task.EndTime.String() && !task.EndTime.Local().IsZero() {
  296. data := list[len(list)-1-i]
  297. data.T_time = task.EndTime.String()
  298. lastMap[v] = data
  299. count += 1
  300. }
  301. break
  302. }
  303. }
  304. }
  305. }
  306. for _, data := range firstMap {
  307. list = append(list, data)
  308. }
  309. for _, data := range lastMap {
  310. list = append(list, data)
  311. }
  312. sort.Slice(list, func(i, j int) bool {
  313. // 先按 T_time 字段排序,如果 T_time 相同则按 T_name 字段排序
  314. if list[i].T_time == list[j].T_time {
  315. return list[i].T_name < list[j].T_name
  316. }
  317. return list[i].T_time > list[j].T_time
  318. })
  319. // 计算总页数
  320. totalPages := (int(count) + c.PageSize - 1) / c.PageSize
  321. // 如果n超出范围,返回错误
  322. if c.Page > totalPages {
  323. return []nats_server.DeviceData_R{}, count, err
  324. }
  325. if c.Page < 1 {
  326. c.Page = 1
  327. }
  328. // 计算当前页的数据
  329. start := (c.Page - 1) * c.PageSize
  330. end := start + c.PageSize
  331. if end > int(count) {
  332. end = int(count)
  333. }
  334. currentPage := list[start:end]
  335. return currentPage, count, err
  336. }
  337. func (e *WaybillTask) GetNewestDataPage(c *dto.WaybillTaskGetNewestDataPageReq) (data nats_server.DeviceData_R, err error) {
  338. var waybill model.Waybill
  339. err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
  340. if err != nil {
  341. e.Log.Errorf("db error: %s", err)
  342. err = errors.New("获取运单信息错误!")
  343. return
  344. }
  345. // 获取公司秘钥
  346. var company model.SysDept
  347. company, err = model.GetCompanyById(waybill.DeptId)
  348. if err != nil {
  349. e.Log.Errorf("db error: %s", err)
  350. err = model.GetCompanyKeyErr
  351. return
  352. }
  353. var taskList []model.WaybillTask
  354. err = e.Orm.Where("waybill_no = ?", c.WaybillNo).Order("id desc").Find(&taskList).Error
  355. if err != nil {
  356. e.Log.Errorf("db error: %s", err)
  357. err = errors.New("获取运单信息任务失败!")
  358. return
  359. }
  360. if len(taskList) == 0 {
  361. err = errors.New("暂无温湿度记录信息!")
  362. return
  363. }
  364. var listAll []nats_server.DeviceData_R
  365. for _, task := range taskList {
  366. deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(task.Sn, company.ColdKey)
  367. if len(deviceSensorList) == 0 {
  368. continue
  369. }
  370. T_snid := fmt.Sprintf("%s,%d|", deviceSensorList[0].T_sn, deviceSensorList[0].T_id)
  371. if len(task.EndTime.String()) == 0 {
  372. task.EndTime = model2.Time(time.Now())
  373. }
  374. // 获取传感器信息
  375. list, _, _ := nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, task.StartTime.String(), task.EndTime.String(), 0, 9999)
  376. if len(list) > 0 {
  377. listAll = append(listAll, list...)
  378. break
  379. }
  380. }
  381. if len(listAll) > 0 {
  382. sort.Slice(listAll, func(i, j int) bool {
  383. return listAll[i].T_time > listAll[j].T_time
  384. })
  385. data = listAll[0]
  386. return
  387. }
  388. err = errors.New("暂无温湿度记录信息!")
  389. return
  390. }
  391. func (e *WaybillTask) GetLocus(c *dto.WaybillGetLocusReq) ([]nats_server.DeviceData_R2, error) {
  392. var err error
  393. var data model.WaybillTask
  394. var waybill model.Waybill
  395. var taskList []model.WaybillTask
  396. locusList := make([]nats_server.DeviceData_R2, 0)
  397. err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
  398. if err != nil {
  399. e.Log.Errorf("db error: %s", err)
  400. return locusList, errors.New("获取运单信息失败")
  401. }
  402. // 获取公司秘钥
  403. var company model.SysDept
  404. company, err = model.GetCompanyById(waybill.DeptId)
  405. if err != nil {
  406. e.Log.Errorf("db error: %s", err)
  407. return locusList, model.GetCompanyKeyErr
  408. }
  409. err = e.Orm.Model(&data).
  410. Scopes(
  411. cDto.MakeCondition(c.GetNeedSearch()),
  412. ).Where("car_id > 0 or cooler_box_id > 0 ").
  413. Find(&taskList).Error
  414. if err != nil {
  415. e.Log.Errorf("db error: %s", err)
  416. return locusList, global.GetFailedErr
  417. }
  418. for i := 0; i < len(taskList); i++ {
  419. // 获取传感器信息
  420. deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(taskList[i].Sn, company.ColdKey)
  421. if len(deviceSensorList) > 0 {
  422. T_snid := fmt.Sprintf("%s,%d|", taskList[i].Sn, deviceSensorList[0].T_id)
  423. dataList, _, err := nats_server.Cold_ReadDeviceDataListBy_T_snidForLocus(T_snid, taskList[i].StartTime.String(), taskList[i].EndTime.String(), 0, 9999)
  424. if err != nil {
  425. e.Log.Errorf("nats 获取轨迹信息失败: %s", err)
  426. return locusList, global.GetFailedErr
  427. }
  428. // 倒序
  429. sort.Slice(dataList, func(i, j int) bool {
  430. if dataList[i].T_time < dataList[j].T_time {
  431. return true
  432. }
  433. return false
  434. })
  435. locusList = append(locusList, dataList...)
  436. }
  437. }
  438. return locusList, nil
  439. }
  440. // Update 修改Waybill对象
  441. func (e *WaybillTask) Update(c *dto.WaybillTaskUpdateReq, p *actions.DataPermission) error {
  442. var err error
  443. tx := e.Orm.Begin()
  444. defer func() {
  445. if err != nil {
  446. tx.Rollback()
  447. } else {
  448. tx.Commit()
  449. }
  450. }()
  451. for _, task := range c.WaybillTaskList {
  452. var waybillTaskModel = model.WaybillTask{}
  453. // 查询运单是否存在
  454. err = e.Orm.Scopes(actions.Permission(waybillTaskModel.TableName(), p)).
  455. First(&waybillTaskModel, task.Id).Error
  456. if err != nil {
  457. e.Log.Errorf("db error: %s", err)
  458. if errors.Is(err, gorm.ErrRecordNotFound) {
  459. return global.UpdateNotFoundOrNoPermissionErr
  460. }
  461. return global.UpdateFailedErr
  462. }
  463. oldStartTime := waybillTaskModel.StartTime
  464. oldEndTime := waybillTaskModel.EndTime
  465. // 修改运单物流时间
  466. if waybillTaskModel.StartTime != task.StartTime {
  467. var waybillLogistics = model.WaybillLogistics{}
  468. // 查询运单是否存在
  469. err = e.Orm.Scopes(actions.Permission(waybillLogistics.TableName(), p)).
  470. Where("created_at = ?", oldStartTime).First(&waybillLogistics).Error
  471. if err != nil {
  472. e.Log.Errorf("db error: %s", err)
  473. if errors.Is(err, gorm.ErrRecordNotFound) {
  474. return global.UpdateNotFoundOrNoPermissionErr
  475. }
  476. return global.UpdateFailedErr
  477. }
  478. waybillLogistics.CreatedAt = task.StartTime
  479. err = tx.Save(&waybillLogistics).Error
  480. if err != nil {
  481. e.Log.Errorf("db error: %s", err)
  482. return global.UpdateFailedErr
  483. }
  484. }
  485. // 修改运单物流时间
  486. if waybillTaskModel.EndTime != task.EndTime {
  487. var waybillLogistics = model.WaybillLogistics{}
  488. // 查询运单是否存在
  489. err = e.Orm.Scopes(actions.Permission(waybillLogistics.TableName(), p)).
  490. Where("created_at = ? and status != ?", oldEndTime, model.WaybillStatusReceipt).Last(&waybillLogistics).Error
  491. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  492. e.Log.Errorf("db error: %s", err)
  493. return global.UpdateFailedErr
  494. }
  495. if waybillLogistics.Id > 0 {
  496. waybillLogistics.CreatedAt = task.EndTime
  497. err = tx.Save(&waybillLogistics).Error
  498. if err != nil {
  499. e.Log.Errorf("db error: %s", err)
  500. return global.UpdateFailedErr
  501. }
  502. }
  503. }
  504. // 修改运单物流时间
  505. if waybillTaskModel.EndTime != task.EndTime {
  506. var waybillLogistics = model.WaybillLogistics{}
  507. // 查询运单是否存在
  508. err = e.Orm.Scopes(actions.Permission(waybillLogistics.TableName(), p)).
  509. Where("created_at = ? and status = ?", oldEndTime, model.WaybillStatusReceipt).Last(&waybillLogistics).Error
  510. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  511. e.Log.Errorf("db error: %s", err)
  512. return global.UpdateFailedErr
  513. }
  514. if waybillLogistics.Id > 0 {
  515. waybillLogistics.CreatedAt = task.EndTime
  516. err = tx.Save(&waybillLogistics).Error
  517. if err != nil {
  518. e.Log.Errorf("db error: %s", err)
  519. return global.UpdateFailedErr
  520. }
  521. // 修改运单签收时间
  522. var waybillModel = model.Waybill{}
  523. // 查询运单是否存在
  524. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  525. Where("waybill_no = ?", waybillLogistics.WaybillNo).
  526. First(&waybillModel).Error
  527. if err != nil {
  528. e.Log.Errorf("db error: %s", err)
  529. if errors.Is(err, gorm.ErrRecordNotFound) {
  530. return errors.New(fmt.Sprintf("运单号%s不存在", waybillLogistics.WaybillNo))
  531. }
  532. return errors.New(fmt.Sprintf("运单号%s查询失败", waybillLogistics.WaybillNo))
  533. }
  534. waybillModel.ReceiptTime = task.StartTime
  535. err = tx.Save(&waybillModel).Error
  536. if err != nil {
  537. e.Log.Errorf("db error: %s", err)
  538. return errors.New(fmt.Sprintf("保存运单信息失败:%s", err))
  539. }
  540. }
  541. }
  542. waybillTaskModel.StartTime = task.StartTime
  543. waybillTaskModel.EndTime = task.EndTime
  544. waybillTaskModel.UpdateBy = c.UpdateBy
  545. err = tx.Save(&waybillTaskModel).Error
  546. if err != nil {
  547. e.Log.Errorf("db error: %s", err)
  548. return global.UpdateFailedErr
  549. }
  550. }
  551. return nil
  552. }