waybill.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. package service
  2. import (
  3. "cold-delivery/app/admin/model"
  4. "cold-delivery/app/admin/service/dto"
  5. "cold-delivery/common/actions"
  6. cDto "cold-delivery/common/dto"
  7. "cold-delivery/common/global"
  8. "cold-delivery/common/lib"
  9. model2 "cold-delivery/common/model"
  10. "cold-delivery/common/nats/nats_server"
  11. "cold-delivery/conf"
  12. "errors"
  13. "fmt"
  14. "go.uber.org/zap"
  15. "gogs.baozhida.cn/zoie/OAuth-core/pkg/sms"
  16. "gogs.baozhida.cn/zoie/OAuth-core/pkg/utils"
  17. "gogs.baozhida.cn/zoie/OAuth-core/service"
  18. "gorm.io/gorm"
  19. "sort"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. type Waybill struct {
  25. service.Service
  26. }
  27. // GetPage 获取Waybill列表
  28. func (e *Waybill) GetPage(c *dto.WaybillGetPageReq, list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  29. var err error
  30. var data model.Waybill
  31. if c.PageSize == 9999 {
  32. err = e.Orm.Model(&data).
  33. Scopes(
  34. cDto.MakeCondition(c.GetNeedSearch()),
  35. actions.Permission(data.TableName(), p),
  36. ).
  37. Find(list).Limit(-1).Offset(-1).
  38. Count(count).Error
  39. if err != nil {
  40. e.Log.Errorf("db error: %s", err)
  41. return global.GetFailedErr
  42. }
  43. return nil
  44. }
  45. err = e.Orm.Model(&data).
  46. Scopes(
  47. cDto.MakeCondition(c.GetNeedSearch()),
  48. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  49. actions.Permission(data.TableName(), p),
  50. ).
  51. 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. return nil
  59. }
  60. func (e *Waybill) GetAppletPage(c *dto.WaybillGetAppletPageReq, list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  61. var err error
  62. //var data model.Waybill
  63. var logistics model.WaybillLogistics
  64. err = e.Orm.Table("waybill").
  65. Select("waybill.*,waybill_logistics.status as status").
  66. Scopes(
  67. cDto.MakeCondition(c.GetNeedSearch()),
  68. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  69. actions.Permission(logistics.TableName(), p)).
  70. Where("waybill_logistics.id in (SELECT MAX(id) FROM waybill_logistics where user_id = ? group by waybill_no )", p.UserId).
  71. Joins("left join waybill_logistics on waybill.waybill_no = waybill_logistics.waybill_no").
  72. Find(&list).Limit(-1).Offset(-1).Count(count).Error
  73. if err != nil {
  74. e.Log.Errorf("db error: %s", err)
  75. return global.GetFailedErr
  76. }
  77. return nil
  78. }
  79. func (e *Waybill) GetAppletCount(list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  80. var err error
  81. //var data model.Waybill
  82. var logistics model.WaybillLogistics
  83. err = e.Orm.Table("waybill").
  84. Select("waybill.*,waybill_logistics.status as status").
  85. Scopes(
  86. actions.Permission(logistics.TableName(), p)).
  87. Where("waybill_logistics.id in (SELECT MAX(id) FROM waybill_logistics where user_id = ? group by waybill_no )", p.UserId).
  88. Joins("left join waybill_logistics on waybill.waybill_no = waybill_logistics.waybill_no").
  89. Find(list).Count(count).Error
  90. if err != nil {
  91. e.Log.Errorf("db error: %s", err)
  92. return global.GetFailedErr
  93. }
  94. return nil
  95. }
  96. func (e *Waybill) GetCustomerPage(c *dto.WaybillGetCustomerPageReq, list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  97. var err error
  98. var data model.Waybill
  99. if c.PageSize == 9999 {
  100. err = e.Orm.Model(&data).
  101. Scopes(
  102. cDto.MakeCondition(c.GetNeedSearch()),
  103. actions.Permission(data.TableName(), p),
  104. ).
  105. Find(list).Limit(-1).Offset(-1).
  106. Count(count).Error
  107. if err != nil {
  108. e.Log.Errorf("db error: %s", err)
  109. return global.GetFailedErr
  110. }
  111. return nil
  112. }
  113. err = e.Orm.Model(&data).
  114. Scopes(
  115. cDto.MakeCondition(c.GetNeedSearch()),
  116. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  117. actions.Permission(data.TableName(), p),
  118. ).
  119. Find(list).Limit(-1).Offset(-1).
  120. Count(count).Error
  121. if err != nil {
  122. e.Log.Errorf("db error: %s", err)
  123. return global.GetFailedErr
  124. }
  125. return nil
  126. }
  127. // Get 获取Waybill对象
  128. func (e *Waybill) Get(d *dto.WaybillGetReq, waybillModel *model.Waybill, p *actions.DataPermission) error {
  129. err := e.Orm.
  130. Scopes(actions.Permission(waybillModel.TableName(), p)).
  131. Preload("User").
  132. First(waybillModel, d.GetId()).Error
  133. if err != nil {
  134. e.Log.Errorf("db error: %s", err)
  135. if errors.Is(err, gorm.ErrRecordNotFound) {
  136. return global.GetNotFoundOrNoPermissionErr
  137. }
  138. return global.GetFailedErr
  139. }
  140. return nil
  141. }
  142. func (e *Waybill) GetByWaybillNo(d *dto.WaybillGetByWaybillPdfReq, waybillModel *model.Waybill, p *actions.DataPermission) error {
  143. err := e.Orm.
  144. Scopes(actions.Permission(waybillModel.TableName(), p)).
  145. Where("waybill_no = ?", d.WaybillNo).
  146. Preload("Dept").
  147. First(waybillModel).Error
  148. if err != nil {
  149. e.Log.Errorf("db error: %s", err)
  150. if errors.Is(err, gorm.ErrRecordNotFound) {
  151. return global.GetNotFoundOrNoPermissionErr
  152. }
  153. return global.GetFailedErr
  154. }
  155. return nil
  156. }
  157. // Insert 创建Waybill对象
  158. func (e *Waybill) Insert(c *dto.WaybillInsertReq) error {
  159. var err error
  160. var data model.Waybill
  161. tx := e.Orm.Begin()
  162. defer func() {
  163. if err != nil {
  164. tx.Rollback()
  165. } else {
  166. tx.Commit()
  167. }
  168. }()
  169. var no string
  170. for {
  171. no = time.Now().Format("200601021504") + utils.GetRandString(6, "0123456789", 0)
  172. var j int64
  173. err = e.Orm.Model(&data).Where("waybill_no = ?", no).Count(&j).Error
  174. if err != nil {
  175. continue
  176. }
  177. if j == 0 {
  178. break
  179. }
  180. }
  181. // 添加运单
  182. data.WaybillNo = no
  183. c.Generate(&data)
  184. err = tx.Create(&data).Error
  185. if err != nil {
  186. e.Log.Errorf("db error: %s", err)
  187. return global.CreateFailedErr
  188. }
  189. c.Id = data.Id
  190. return nil
  191. }
  192. // AppletInsert 员工添加运单
  193. func (e *Waybill) AppletInsert(c *dto.WaybillInsertReq, p *actions.DataPermission) error {
  194. var err error
  195. var data model.Waybill
  196. tx := e.Orm.Begin()
  197. defer func() {
  198. if err != nil {
  199. tx.Rollback()
  200. } else {
  201. tx.Commit()
  202. }
  203. }()
  204. var userModel = model.SysUser{}
  205. // 查询运单是否存在
  206. err = tx.Scopes(actions.Permission(userModel.TableName(), p)).
  207. First(&userModel, p.UserId).Error
  208. if err != nil {
  209. e.Log.Errorf("db error: %s", err)
  210. if errors.Is(err, gorm.ErrRecordNotFound) {
  211. return global.GetNotFoundErr
  212. }
  213. return global.CreateFailedErr
  214. }
  215. if (userModel.Type != model.SysUserTypeDriver && userModel.Type != model.SysUserTypeWarehouse) && userModel.UserType != "customer" {
  216. err = errors.New("无权添加!")
  217. return err
  218. }
  219. var status = model.WaybillStatusWaitDelivery
  220. var coolerBox = model.CoolerBox{}
  221. // 查询保温箱信息
  222. err = tx.Scopes(actions.Permission(coolerBox.TableName(), p)).
  223. First(&coolerBox, c.CoolerBoxId).Error
  224. if err != nil {
  225. e.Log.Errorf("db error: %s", err)
  226. return errors.New("获取车辆信息失败")
  227. }
  228. var no string
  229. for {
  230. no = time.Now().Format("200601021504") + utils.GetRandString(6, "0123456789", 0)
  231. var j int64
  232. err = e.Orm.Model(&data).Where("waybill_no = ?", no).Count(&j).Error
  233. if err != nil {
  234. continue
  235. }
  236. if j == 0 {
  237. break
  238. }
  239. }
  240. // 添加运单
  241. data.DeptId = p.DeptId
  242. data.CreateBy = p.UserId
  243. data.WaybillNo = no
  244. c.Generate(&data)
  245. data.Status = status
  246. err = tx.Create(&data).Error
  247. if err != nil {
  248. e.Log.Errorf("db error: %s", err)
  249. return global.CreateFailedErr
  250. }
  251. c.Id = data.Id
  252. // 添加物流
  253. Logistics := model.WaybillLogistics{
  254. WaybillNo: data.WaybillNo,
  255. Status: data.Status,
  256. CoolerBoxId: coolerBox.Id,
  257. UserId: p.UserId,
  258. ControlBy: model2.ControlBy{
  259. CreateBy: p.UserId,
  260. },
  261. DeptBy: model2.DeptBy{
  262. DeptId: p.DeptId,
  263. },
  264. }
  265. err = tx.Create(&Logistics).Error
  266. if err != nil {
  267. e.Log.Errorf("db error: %s", err)
  268. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  269. }
  270. return nil
  271. }
  272. // Update 修改Waybill对象
  273. func (e *Waybill) Update(c *dto.WaybillUpdateReq, p *actions.DataPermission) error {
  274. var err error
  275. tx := e.Orm.Begin()
  276. defer func() {
  277. if err != nil {
  278. tx.Rollback()
  279. } else {
  280. tx.Commit()
  281. }
  282. }()
  283. var waybillModel = model.Waybill{}
  284. // 查询运单是否存在
  285. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  286. First(&waybillModel, c.GetId()).Error
  287. if err != nil {
  288. e.Log.Errorf("db error: %s", err)
  289. if errors.Is(err, gorm.ErrRecordNotFound) {
  290. return global.UpdateNotFoundOrNoPermissionErr
  291. }
  292. return global.UpdateFailedErr
  293. }
  294. c.Generate(&waybillModel)
  295. err = tx.Save(&waybillModel).Error
  296. if err != nil {
  297. e.Log.Errorf("db error: %s", err)
  298. return global.UpdateFailedErr
  299. }
  300. c.Id = waybillModel.Id
  301. return nil
  302. }
  303. func (e *Waybill) UpdateStatus(c *dto.WaybillUpdateStatusReq, p *actions.DataPermission) error {
  304. var err error
  305. tx := e.Orm.Begin()
  306. defer func() {
  307. if err != nil {
  308. tx.Rollback()
  309. } else {
  310. tx.Commit()
  311. }
  312. }()
  313. var waybillModel = model.Waybill{}
  314. // 查询运单是否存在
  315. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  316. First(&waybillModel, c.GetId()).Error
  317. if err != nil {
  318. e.Log.Errorf("db error: %s", err)
  319. if errors.Is(err, gorm.ErrRecordNotFound) {
  320. return global.UpdateNotFoundOrNoPermissionErr
  321. }
  322. return global.UpdateFailedErr
  323. }
  324. c.Generate(&waybillModel)
  325. err = tx.Save(&waybillModel).Error
  326. if err != nil {
  327. e.Log.Errorf("db error: %s", err)
  328. return global.UpdateFailedErr
  329. }
  330. c.Id = waybillModel.Id
  331. return nil
  332. }
  333. func (e *Waybill) Delivery(c *dto.WaybillDeliveryReq, p *actions.DataPermission) error {
  334. var err error
  335. tx := e.Orm.Begin()
  336. defer func() {
  337. if err != nil {
  338. tx.Rollback()
  339. } else {
  340. tx.Commit()
  341. }
  342. }()
  343. var coolerBox = model.CoolerBox{}
  344. // 查询保温箱信息
  345. err = tx.Scopes(actions.Permission(coolerBox.TableName(), p)).
  346. First(&coolerBox, c.CoolerBoxId).Error
  347. if err != nil {
  348. e.Log.Errorf("db error: %s", err)
  349. return errors.New("获取保温箱信息失败")
  350. }
  351. for _, id := range c.WaybillIds {
  352. var waybillModel = model.Waybill{}
  353. // 查询运单是否存在
  354. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  355. First(&waybillModel, id).Error
  356. if err != nil {
  357. e.Log.Errorf("db error: %s", err)
  358. if errors.Is(err, gorm.ErrRecordNotFound) {
  359. return global.UpdateNotFoundOrNoPermissionErr
  360. }
  361. return global.UpdateFailedErr
  362. }
  363. if waybillModel.Status == model.WaybillStatusWaitDelivery || (waybillModel.Status == model.WaybillStatusInDelivery && waybillModel.CoolerBoxId != c.CoolerBoxId) {
  364. waybillModel.Status = model.WaybillStatusInDelivery
  365. waybillModel.CoolerBoxId = c.CoolerBoxId
  366. waybillModel.DeliveryTime = model2.Time(time.Now())
  367. err = tx.Save(&waybillModel).Error
  368. if err != nil {
  369. e.Log.Errorf("db error: %s", err)
  370. return global.UpdateFailedErr
  371. }
  372. // 查询任务
  373. var logistics model.WaybillLogistics
  374. err = tx.Model(&logistics).Where("waybill_no = ? and status = ?", waybillModel.WaybillNo, model.WaybillStatusInDelivery).
  375. Last(&logistics).Error
  376. if err != nil {
  377. if errors.Is(err, gorm.ErrRecordNotFound) {
  378. // 添加物流
  379. logisticsObj := model.WaybillLogistics{
  380. WaybillNo: waybillModel.WaybillNo,
  381. Status: waybillModel.Status,
  382. CoolerBoxId: coolerBox.Id,
  383. ControlBy: model2.ControlBy{
  384. CreateBy: p.UserId,
  385. },
  386. DeptBy: model2.DeptBy{
  387. DeptId: p.DeptId,
  388. },
  389. }
  390. err = tx.Create(&logisticsObj).Error
  391. if err != nil {
  392. e.Log.Errorf("db error: %s", err)
  393. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  394. }
  395. } else {
  396. e.Log.Errorf("db error: %s", err)
  397. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  398. }
  399. }
  400. logistics.CoolerBoxId = coolerBox.Id
  401. err = tx.Save(&logistics).Error
  402. if err != nil {
  403. e.Log.Errorf("db error: %s", err)
  404. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  405. }
  406. // 查询任务
  407. var task model.WaybillTask
  408. err = tx.Model(&task).Where("waybill_no = ? ", waybillModel.WaybillNo).
  409. Last(&task).Error
  410. if err != nil {
  411. if errors.Is(err, gorm.ErrRecordNotFound) {
  412. // 添加任务
  413. taskObj := model.WaybillTask{
  414. WaybillNo: waybillModel.WaybillNo,
  415. CoolerBoxId: coolerBox.Id,
  416. UserId: p.UserId,
  417. Sn: coolerBox.Sn,
  418. StartTime: model2.Time(time.Now()),
  419. ControlBy: model2.ControlBy{
  420. CreateBy: p.UserId,
  421. },
  422. DeptBy: model2.DeptBy{
  423. DeptId: p.DeptId,
  424. },
  425. }
  426. err = tx.Create(&taskObj).Error
  427. if err != nil {
  428. e.Log.Errorf("db error: %s", err)
  429. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  430. }
  431. } else {
  432. e.Log.Errorf("db error: %s", err)
  433. return errors.New(fmt.Sprintf("查询运单任务信息失败:%s", err))
  434. }
  435. }
  436. task.StartTime = model2.Time(time.Now())
  437. task.UpdateBy = p.UserId
  438. task.CoolerBoxId = coolerBox.Id
  439. task.Sn = coolerBox.Sn
  440. err = tx.Save(&task).Error
  441. if err != nil {
  442. e.Log.Errorf("db error: %s", err)
  443. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  444. }
  445. //if logistics.Id == 0 {
  446. // ss := sms.NewSMS(conf.ExtConfig.SubMail.Appid, conf.ExtConfig.SubMail.Signature)
  447. // res, err1 := ss.SmsXSend(waybillModel.ConsigneeAddressPhone, lib.AesEncryptCBC(waybillModel.WaybillNo, lib.AesKey))
  448. // if err1 != nil || res.Status != sms.SUCCESS {
  449. // e.Log.Errorf("发送短信验证码出现异常", zap.Any("res", res), zap.Error(err1))
  450. // err = errors.New("验证吗发送失败,请重试")
  451. // return err
  452. // }
  453. //}
  454. ss := sms.NewSMS(conf.ExtConfig.SubMail.Appid, conf.ExtConfig.SubMail.Signature)
  455. addr := conf.ExtConfig.Applet.WaybillUrl + lib.AesEncryptCBC(waybillModel.WaybillNo, lib.AesKey)
  456. res, err1 := ss.SmsXSend(waybillModel.ConsigneeAddressPhone, addr)
  457. if err1 != nil || res.Status != sms.SUCCESS {
  458. e.Log.Errorf("发送短信验证码出现异常", zap.Any("res", res), zap.Error(err1))
  459. err = errors.New("验证吗发送失败,请重试")
  460. return err
  461. }
  462. waybillModel.SendLog = model.WaybillSendLog{
  463. Phone: waybillModel.ConsigneeAddressPhone,
  464. Content: "【冷链送药平台】您的订单正在派送中,点击查看详情:" + addr,
  465. }
  466. }
  467. }
  468. return nil
  469. }
  470. // Remove 删除Waybill
  471. func (e *Waybill) Remove(c *dto.WaybillDeleteReq, p *actions.DataPermission) error {
  472. var err error
  473. tx := e.Orm.Begin()
  474. defer func() {
  475. if err != nil {
  476. tx.Rollback()
  477. } else {
  478. tx.Commit()
  479. }
  480. }()
  481. var waybillModel model.Waybill
  482. // 查询运单是否存在
  483. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  484. First(&waybillModel, c.GetId()).Error
  485. if err != nil {
  486. e.Log.Errorf("db error: %s", err)
  487. if errors.Is(err, gorm.ErrRecordNotFound) {
  488. return global.DeleteNotFoundOrNoPermissionErr
  489. }
  490. return global.DeleteFailedErr
  491. }
  492. if waybillModel.Status != model.WaybillStatusWaitDelivery {
  493. return errors.New(fmt.Sprintf("运单状态为%s,禁止删除", model.WaybillStatusMap[waybillModel.Status]))
  494. }
  495. db := tx.Delete(&waybillModel)
  496. if err = db.Error; err != nil {
  497. e.Log.Errorf("db error: %s", err)
  498. return global.DeleteFailedErr
  499. }
  500. if db.RowsAffected == 0 {
  501. return global.DeleteNotFoundOrNoPermissionErr
  502. }
  503. return nil
  504. }
  505. func (e *Waybill) Receipt(c *dto.WaybillReceiptReq, p *actions.DataPermission) error {
  506. var err error
  507. tx := e.Orm.Begin()
  508. defer func() {
  509. if err != nil {
  510. tx.Rollback()
  511. } else {
  512. tx.Commit()
  513. }
  514. }()
  515. var waybillModel = model.Waybill{}
  516. // 查询运单是否存在
  517. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  518. Where("waybill_no = ?", c.WaybillNo).
  519. First(&waybillModel).Error
  520. if err != nil {
  521. e.Log.Errorf("db error: %s", err)
  522. if errors.Is(err, gorm.ErrRecordNotFound) {
  523. return errors.New(fmt.Sprintf("运单号%s不存在", c.WaybillNo))
  524. }
  525. return errors.New(fmt.Sprintf("运单号%s查询失败", c.WaybillNo))
  526. }
  527. // 查询保温箱信息
  528. var coolerBox = model.CoolerBox{}
  529. err = tx.Scopes(actions.Permission(coolerBox.TableName(), p)).
  530. First(&coolerBox, waybillModel.CoolerBoxId).Error
  531. if err != nil {
  532. e.Log.Errorf("db error: %s", err)
  533. return errors.New("获取保温箱信息失败")
  534. }
  535. if waybillModel.Status == model.WaybillStatusWaitDelivery {
  536. err = errors.New(fmt.Sprintf("运单状态为%s,禁止操作", model.WaybillStatusMap[waybillModel.Status]))
  537. return err
  538. }
  539. if waybillModel.Status == model.WaybillStatusReceipt || waybillModel.Status == model.WaybillStatusRejection {
  540. return nil
  541. }
  542. waybillModel.Status = c.Status
  543. waybillModel.RejectionReason = c.RejectionReason
  544. waybillModel.ReceiptTime = model2.Time(time.Now())
  545. waybillModel.ReceiptImg = c.ReceiptImg
  546. err = tx.Save(&waybillModel).Error
  547. if err != nil {
  548. e.Log.Errorf("db error: %s", err)
  549. return errors.New(fmt.Sprintf("保存运单信息失败:%s", err))
  550. }
  551. var lng, lat string
  552. lng, lat, err = e.GetSite(p.DeptId, coolerBox.Sn, waybillModel.ReceiptTime.String())
  553. if err != nil {
  554. e.Log.Errorf("获取定位信息失败: %s", err)
  555. return err
  556. }
  557. // 查询任务
  558. var task model.WaybillTask
  559. err = tx.Model(&task).Where("waybill_no = ? and cooler_box_id = ?", c.WaybillNo, coolerBox.Id).
  560. Last(&task).Error
  561. if err != nil {
  562. e.Log.Errorf("db error: %s", err)
  563. return errors.New(fmt.Sprintf("查询运单任务信息失败:%s", err))
  564. }
  565. // 未下车 直接点签收
  566. if time.Time(task.EndTime).IsZero() {
  567. task.EndTime = model2.Time(time.Now())
  568. task.UpdateBy = p.UserId
  569. err = tx.Save(&task).Error
  570. if err != nil {
  571. e.Log.Errorf("db error: %s", err)
  572. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  573. }
  574. }
  575. // 添加签收记录
  576. Logistics := model.WaybillLogistics{
  577. WaybillNo: c.WaybillNo,
  578. Status: c.Status,
  579. CoolerBoxId: coolerBox.Id,
  580. UserId: p.UserId,
  581. Lng: lng,
  582. Lat: lat,
  583. ControlBy: model2.ControlBy{
  584. CreateBy: p.UserId,
  585. },
  586. DeptBy: model2.DeptBy{
  587. DeptId: p.DeptId,
  588. },
  589. ModelTime: model2.ModelTime{
  590. CreatedAt: waybillModel.ReceiptTime,
  591. },
  592. }
  593. err = tx.Create(&Logistics).Error
  594. if err != nil {
  595. e.Log.Errorf("db error: %s", err)
  596. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  597. }
  598. return nil
  599. }
  600. // 获取入库 出库 上车 下车 定位信息
  601. func (e *Waybill) GetSite(companyId int, sn string, time string) (lng, lat string, err error) {
  602. // 获取公司秘钥
  603. var company model.SysDept
  604. company, err = model.GetCompanyById(companyId)
  605. if err != nil {
  606. e.Log.Errorf("db error: %s", err)
  607. return lng, lat, model.GetCompanyKeyErr
  608. }
  609. // 获取传感器信息
  610. var deviceSensorList = []nats_server.DeviceSensor_R{}
  611. var count int64
  612. deviceSensorList, count, err = nats_server.Cold_CompanyDeviceSensor_List_ByKey(sn, company.ColdKey)
  613. if err != nil || count == 0 {
  614. err = errors.New("查询设备定位信息失败")
  615. return lng, lat, err
  616. }
  617. var deviceData nats_server.DeviceData_
  618. deviceData, err = nats_server.Cold_ReadDeviceDataBy_T_snid_T_time(deviceSensorList[0].T_sn, deviceSensorList[0].T_id, time)
  619. if err != nil {
  620. err = errors.New("查询设备定位信息失败")
  621. return lng, lat, err
  622. }
  623. if len(deviceData.T_site) > 0 {
  624. site := strings.Split(deviceSensorList[0].T_DeviceSensorData.T_site, ",")
  625. if len(site) == 2 {
  626. lng = site[0]
  627. lat = site[1]
  628. }
  629. }
  630. return lng, lat, nil
  631. }
  632. // 获取今日运单数 未派单 未装车 未入库 运送中
  633. // 本月运单总数 上月运单总数 本年运单总数 上年运单总数
  634. func (e *Waybill) GetBasicsStats(c *dto.WaybillStatsReq, p *actions.DataPermission) dto.WaybillStatsRes {
  635. var res dto.WaybillStatsRes
  636. var data model.Waybill
  637. type DateCount struct {
  638. Date string
  639. Count int64
  640. }
  641. yearCount := make([]DateCount, 0)
  642. monthCount := make([]DateCount, 0)
  643. now := time.Now()
  644. todayStartTime := now.Format("2006-01-02") + " 00:00:00"
  645. todayEndTime := now.Format("2006-01-02") + " 23:59:59"
  646. // 获取上个月第一天
  647. firstDayOfLastMonth := time.Date(now.Year(), now.Month()-1, 1, 0, 0, 0, 0, now.Location())
  648. // 获取去年的第一天
  649. firstDayOfLastYear := time.Date(now.Year()-1, time.January, 1, 0, 0, 0, 0, now.Location())
  650. monthStartTime := firstDayOfLastMonth.Format("2006-01-02") + " 00:00:00"
  651. yearStartTime := firstDayOfLastYear.Format("2006-01-02") + " 00:00:00"
  652. // 今日总运单数
  653. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("order_time between ? and ?", todayStartTime, todayEndTime).Count(&res.TodayNum)
  654. // 待派单
  655. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusWaitDelivery).Count(&res.WaitDeliveryNum)
  656. // 配送中
  657. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusInDelivery).Count(&res.InDeliveryNum)
  658. // 已送达
  659. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusReceipt).Count(&res.ReceiptNum)
  660. // 已取消
  661. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusRejection).Count(&res.RejectionNum)
  662. // 获取本月,上月数据
  663. e.Orm.Model(&data).Select("date_format(order_time,'%Y%m') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p)).
  664. Where("order_time between ? and ?", monthStartTime, now).Group("date").Find(&monthCount)
  665. for _, month := range monthCount {
  666. if month.Date == now.Format("200601") {
  667. res.ThisMonthNum = month.Count
  668. }
  669. if month.Date == firstDayOfLastMonth.Format("200601") {
  670. res.LastMonthNum = month.Count
  671. }
  672. }
  673. // 获取本年,上年数据
  674. e.Orm.Model(&data).Select("date_format(order_time,'%Y') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p)).
  675. Where("order_time between ? and ?", yearStartTime, now).Group("date").Find(&yearCount)
  676. for _, month := range yearCount {
  677. if month.Date == now.Format("2006") {
  678. res.ThisYearNum = month.Count
  679. }
  680. if month.Date == firstDayOfLastYear.Format("2006") {
  681. res.LastYearNum = month.Count
  682. }
  683. }
  684. if c.Type == "year" {
  685. // 获取上个月第一天
  686. year, _ := strconv.Atoi(c.Date)
  687. firstDayOfyear := time.Date(year, 1, 1, 0, 0, 0, 0, now.Location())
  688. lastDayOfyear := time.Date(year, 12, 31, 23, 59, 59, 0, now.Location())
  689. // 年度数据统计
  690. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p)).
  691. Where("order_time between ? and ?", firstDayOfyear, lastDayOfyear).Group("date").Find(&res.Stats)
  692. }
  693. if c.Type == "month" {
  694. // 获取上个月第一天
  695. month, _ := time.Parse("2006-01", c.Date)
  696. firstDayOfMonth := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, now.Location())
  697. lastDayOfMonth := time.Date(month.Year(), month.Month()+1, 1, 23, 59, 59, 0, now.Location()).Add(-time.Hour * 24)
  698. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m-%d') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p)).
  699. Where("order_time between ? and ?", firstDayOfMonth, lastDayOfMonth).Group("date").Find(&res.Stats)
  700. }
  701. return res
  702. }
  703. // 获取运单所有温湿度素具
  704. func (e *Waybill) GetAllData(c *dto.WaybillGetByWaybillNoReq) ([]nats_server.DeviceData_R, []WaybillPDF, error) {
  705. var err error
  706. var data model.WaybillTask
  707. var waybill model.Waybill
  708. var taskList []model.WaybillTask
  709. var waybillPDF []WaybillPDF
  710. dataList := make([]nats_server.DeviceData_R, 0)
  711. err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
  712. if err != nil {
  713. e.Log.Errorf("db error: %s", err)
  714. return dataList, waybillPDF, errors.New("获取运单信息失败")
  715. }
  716. // 未签收,不返回数据
  717. if waybill.Status != model.WaybillStatusReceipt {
  718. return dataList, waybillPDF, nil
  719. }
  720. // 获取公司秘钥
  721. var company model.SysDept
  722. company, err = model.GetCompanyById(waybill.DeptId)
  723. if err != nil {
  724. e.Log.Errorf("db error: %s", err)
  725. return dataList, waybillPDF, model.GetCompanyKeyErr
  726. }
  727. err = e.Orm.Model(&data).
  728. Where("waybill_no = ?", c.WaybillNo).
  729. Order("id desc").
  730. Find(&taskList).Error
  731. if err != nil {
  732. e.Log.Errorf("db error: %s", err)
  733. return dataList, waybillPDF, global.GetFailedErr
  734. }
  735. // 获取最后一个任务id
  736. var lastWaybillTask model.WaybillTask
  737. err = e.Orm.Model(&lastWaybillTask).Where("waybill_no = ?", c.WaybillNo).Last(&lastWaybillTask).Error
  738. if err != nil {
  739. e.Log.Errorf("db error: %s", err)
  740. err = errors.New("获取运单信息错误!")
  741. return dataList, waybillPDF, err
  742. }
  743. // 创建名称到权重的映射
  744. orderMap := make(map[string]int)
  745. for i, v := range taskList {
  746. orderMap[v.Sn] = i
  747. }
  748. for i := 0; i < len(taskList); i++ {
  749. // 获取传感器信息
  750. deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(taskList[i].Sn, company.ColdKey)
  751. var T_snid string
  752. var list []nats_server.DeviceData_R
  753. for _, r := range deviceSensorList {
  754. T_snid += fmt.Sprintf("%s,%d|", r.T_sn, r.T_id)
  755. }
  756. var count int64
  757. list, count, err = nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, taskList[i].StartTime.String(), taskList[i].EndTime.String(), 0, 9999)
  758. if err != nil {
  759. e.Log.Errorf("nats 获取温湿度信息失败: %s", err)
  760. return dataList, waybillPDF, global.GetFailedErr
  761. }
  762. firstMap := map[int]nats_server.DeviceData_R{}
  763. lastMap := map[int]nats_server.DeviceData_R{}
  764. if count > 0 {
  765. for _, v := range deviceSensorList {
  766. for j := 0; j < len(list); j++ {
  767. if v.T_id == list[j].T_id {
  768. if list[j].T_time != taskList[i].StartTime.String() {
  769. firstData := list[j]
  770. firstData.T_time = taskList[i].StartTime.String()
  771. firstMap[v.T_id] = firstData
  772. count += 1
  773. }
  774. break
  775. }
  776. }
  777. if waybill.Status == model.WaybillStatusReceipt {
  778. for k := len(list) - 1; k >= 0; k-- {
  779. if v.T_id == list[k].T_id {
  780. if taskList[i].Id == lastWaybillTask.Id && list[k].T_time != taskList[i].EndTime.String() && !time.Time(taskList[i].EndTime).IsZero() {
  781. lastData := list[k]
  782. lastData.T_time = taskList[i].EndTime.String()
  783. lastMap[v.T_id] = lastData
  784. count += 1
  785. }
  786. break
  787. }
  788. }
  789. }
  790. }
  791. }
  792. for _, v := range firstMap {
  793. list = append(list, v)
  794. }
  795. for _, v := range lastMap {
  796. list = append(list, v)
  797. }
  798. sort.Slice(list, func(x, y int) bool {
  799. if list[x].T_time == list[y].T_time {
  800. // 如果时间相同,则按预设顺序排序
  801. return orderMap[list[x].T_sn] < orderMap[list[y].T_sn]
  802. }
  803. return list[x].T_time > list[y].T_time
  804. })
  805. dataList = append(dataList, list...)
  806. waybillPDF = append(waybillPDF, WaybillPDF{
  807. Data: list,
  808. DeviceSensorList: deviceSensorList,
  809. Task: taskList[i],
  810. })
  811. }
  812. sort.Slice(dataList, func(i, j int) bool {
  813. if dataList[i].T_time == dataList[j].T_time {
  814. // 如果时间相同,则按预设顺序排序
  815. return orderMap[dataList[i].T_sn] < orderMap[dataList[j].T_sn]
  816. }
  817. return dataList[i].T_time < dataList[j].T_time
  818. })
  819. return dataList, waybillPDF, nil
  820. }
  821. type WaybillPDF struct {
  822. Data []nats_server.DeviceData_R `json:"data"`
  823. DeviceSensorList []nats_server.DeviceSensor_R `json:"deviceSensorList"`
  824. Task model.WaybillTask `json:"task"`
  825. }