waybill.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  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. "net/url"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "time"
  24. )
  25. type Waybill struct {
  26. service.Service
  27. }
  28. // GetPage 获取Waybill列表
  29. func (e *Waybill) GetPage(c *dto.WaybillGetPageReq, list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  30. var err error
  31. var data model.Waybill
  32. if c.PageSize == 9999 {
  33. err = e.Orm.Model(&data).
  34. Scopes(
  35. cDto.MakeCondition(c.GetNeedSearch()),
  36. actions.Permission(data.TableName(), p),
  37. ).
  38. Preload("CoolerBox").
  39. Preload("Delivery").
  40. Preload("ReCheck").
  41. Find(list).Limit(-1).Offset(-1).
  42. Count(count).Error
  43. if err != nil {
  44. e.Log.Errorf("db error: %s", err)
  45. return global.GetFailedErr
  46. }
  47. return nil
  48. }
  49. err = e.Orm.Model(&data).
  50. Scopes(
  51. cDto.MakeCondition(c.GetNeedSearch()),
  52. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  53. actions.Permission(data.TableName(), p),
  54. ).
  55. Preload("CoolerBox").
  56. Preload("Delivery").
  57. Preload("ReCheck").
  58. Find(list).Limit(-1).Offset(-1).
  59. Count(count).Error
  60. if err != nil {
  61. e.Log.Errorf("db error: %s", err)
  62. return global.GetFailedErr
  63. }
  64. return nil
  65. }
  66. func (e *Waybill) GetUserPage(c *dto.WaybillGetPageReq, list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  67. var err error
  68. var data model.Waybill
  69. if c.PageSize == 9999 {
  70. err = e.Orm.Model(&data).
  71. Scopes(
  72. cDto.MakeCondition(c.GetNeedSearch()),
  73. ).
  74. Where("create_by = ?", p.UserId).
  75. Find(list).Limit(-1).Offset(-1).
  76. Count(count).Error
  77. if err != nil {
  78. e.Log.Errorf("db error: %s", err)
  79. return global.GetFailedErr
  80. }
  81. return nil
  82. }
  83. err = e.Orm.Model(&data).
  84. Scopes(
  85. cDto.MakeCondition(c.GetNeedSearch()),
  86. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  87. ).
  88. Where("delivery_id = ? or re_check_id = ? or create_by = ?", p.UserId, p.UserId, p.UserId).
  89. Preload("CoolerBox").
  90. Preload("Delivery").
  91. Preload("ReCheck").
  92. Find(list).Limit(-1).Offset(-1).
  93. Count(count).Error
  94. if err != nil {
  95. e.Log.Errorf("db error: %s", err)
  96. return global.GetFailedErr
  97. }
  98. return nil
  99. }
  100. func (e *Waybill) GetAppletPage(c *dto.WaybillGetAppletPageReq, list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  101. var err error
  102. //var data model.Waybill
  103. var logistics model.WaybillLogistics
  104. err = e.Orm.Table("waybill").
  105. Select("waybill.*,waybill_logistics.status as status").
  106. Scopes(
  107. cDto.MakeCondition(c.GetNeedSearch()),
  108. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  109. actions.Permission(logistics.TableName(), p)).
  110. Where("waybill_logistics.id in (SELECT MAX(id) FROM waybill_logistics where user_id = ? group by waybill_no )", p.UserId).
  111. Joins("left join waybill_logistics on waybill.waybill_no = waybill_logistics.waybill_no").
  112. Find(&list).Limit(-1).Offset(-1).Count(count).Error
  113. if err != nil {
  114. e.Log.Errorf("db error: %s", err)
  115. return global.GetFailedErr
  116. }
  117. return nil
  118. }
  119. func (e *Waybill) GetAppletCount(list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  120. var err error
  121. //var data model.Waybill
  122. var logistics model.WaybillLogistics
  123. err = e.Orm.Table("waybill").
  124. Select("waybill.*,waybill_logistics.status as status").
  125. Scopes(
  126. actions.Permission(logistics.TableName(), p)).
  127. Where("waybill_logistics.id in (SELECT MAX(id) FROM waybill_logistics where user_id = ? group by waybill_no )", p.UserId).
  128. Joins("left join waybill_logistics on waybill.waybill_no = waybill_logistics.waybill_no").
  129. Find(list).Count(count).Error
  130. if err != nil {
  131. e.Log.Errorf("db error: %s", err)
  132. return global.GetFailedErr
  133. }
  134. return nil
  135. }
  136. func (e *Waybill) GetCustomerPage(c *dto.WaybillGetCustomerPageReq, list *[]model.Waybill, count *int64, p *actions.DataPermission) error {
  137. var err error
  138. var data model.Waybill
  139. if c.PageSize == 9999 {
  140. err = e.Orm.Model(&data).
  141. Scopes(
  142. cDto.MakeCondition(c.GetNeedSearch()),
  143. actions.Permission(data.TableName(), p),
  144. ).
  145. Find(list).Limit(-1).Offset(-1).
  146. Count(count).Error
  147. if err != nil {
  148. e.Log.Errorf("db error: %s", err)
  149. return global.GetFailedErr
  150. }
  151. return nil
  152. }
  153. err = e.Orm.Model(&data).
  154. Scopes(
  155. cDto.MakeCondition(c.GetNeedSearch()),
  156. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  157. actions.Permission(data.TableName(), p),
  158. ).
  159. Find(list).Limit(-1).Offset(-1).
  160. Count(count).Error
  161. if err != nil {
  162. e.Log.Errorf("db error: %s", err)
  163. return global.GetFailedErr
  164. }
  165. return nil
  166. }
  167. // Get 获取Waybill对象
  168. func (e *Waybill) Get(d *dto.WaybillGetReq, waybillModel *model.Waybill, p *actions.DataPermission) error {
  169. err := e.Orm.
  170. Scopes(actions.Permission(waybillModel.TableName(), p)).
  171. Preload("User").
  172. First(waybillModel, d.GetId()).Error
  173. if err != nil {
  174. e.Log.Errorf("db error: %s", err)
  175. if errors.Is(err, gorm.ErrRecordNotFound) {
  176. return global.GetNotFoundOrNoPermissionErr
  177. }
  178. return global.GetFailedErr
  179. }
  180. return nil
  181. }
  182. func (e *Waybill) GetByWaybillNo(d *dto.WaybillGetByWaybillPdfReq, waybillModel *model.Waybill, p *actions.DataPermission) error {
  183. err := e.Orm.
  184. Scopes(actions.Permission(waybillModel.TableName(), p)).
  185. Where("waybill_no = ?", d.WaybillNo).
  186. Preload("Dept").
  187. Preload("CoolerBox").
  188. Preload("Delivery").
  189. Preload("ReCheck").
  190. First(waybillModel).Error
  191. if err != nil {
  192. e.Log.Errorf("db error: %s", err)
  193. if errors.Is(err, gorm.ErrRecordNotFound) {
  194. return global.GetNotFoundOrNoPermissionErr
  195. }
  196. return global.GetFailedErr
  197. }
  198. return nil
  199. }
  200. // Insert 创建Waybill对象
  201. func (e *Waybill) Insert(c *dto.WaybillInsertReq) error {
  202. var err error
  203. var data model.Waybill
  204. tx := e.Orm.Begin()
  205. defer func() {
  206. if err != nil {
  207. tx.Rollback()
  208. } else {
  209. tx.Commit()
  210. }
  211. }()
  212. var no string
  213. for {
  214. no = time.Now().Format("200601021504") + utils.GetRandString(6, "0123456789", 0)
  215. var j int64
  216. err = e.Orm.Model(&data).Where("waybill_no = ?", no).Count(&j).Error
  217. if err != nil {
  218. continue
  219. }
  220. if j == 0 {
  221. break
  222. }
  223. }
  224. // 添加运单
  225. data.WaybillNo = no
  226. c.Generate(&data)
  227. err = tx.Create(&data).Error
  228. if err != nil {
  229. e.Log.Errorf("db error: %s", err)
  230. return global.CreateFailedErr
  231. }
  232. c.Id = data.Id
  233. // 保存收货地址
  234. //if c.SaveSenderAddress {
  235. // // 查询地址是否存在
  236. // address := model.Address{}
  237. // err = e.Orm.Where("address = ? and phone = ? and name = ? and dept_id = ? and address_type = 'sender'",
  238. // c.SenderAddressDetails, c.SenderAddressPhone, c.SenderAddressName, c.DeptId).First(&address).Error
  239. // if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  240. // address.Address = c.SenderAddressDetails
  241. // address.Phone = c.SenderAddressPhone
  242. // address.Name = c.SenderAddressName
  243. // address.DeptId = c.DeptId
  244. // address.AddressType = "sender"
  245. // err = tx.Create(&address).Error
  246. // if err != nil {
  247. // e.Log.Errorf("创建地址失败: %s", err)
  248. // return global.CreateFailedErr
  249. // }
  250. // }
  251. //}
  252. // 保存发货地址
  253. if c.SaveConsigneeAddress {
  254. // 查询地址是否存在
  255. address := model.Address{}
  256. err = e.Orm.Where("address = ? and phone = ? and name = ? and dept_id = ? and address_type = 'consignee'",
  257. c.ConsigneeAddressDetails, c.ConsigneeAddressPhone, c.ConsigneeAddressName, c.DeptId).First(&address).Error
  258. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  259. address.Address = c.ConsigneeAddressDetails
  260. address.Phone = c.ConsigneeAddressPhone
  261. address.Name = c.ConsigneeAddressName
  262. address.DeptId = c.DeptId
  263. address.AddressType = "consignee"
  264. err = tx.Create(&address).Error
  265. if err != nil {
  266. e.Log.Errorf("创建地址失败: %s", err)
  267. return global.CreateFailedErr
  268. }
  269. }
  270. }
  271. return nil
  272. }
  273. // Update 修改Waybill对象
  274. func (e *Waybill) Update(c *dto.WaybillUpdateReq, p *actions.DataPermission) error {
  275. var err error
  276. tx := e.Orm.Begin()
  277. defer func() {
  278. if err != nil {
  279. tx.Rollback()
  280. } else {
  281. tx.Commit()
  282. }
  283. }()
  284. var waybillModel = model.Waybill{}
  285. // 查询运单是否存在
  286. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  287. First(&waybillModel, c.GetId()).Error
  288. if err != nil {
  289. e.Log.Errorf("db error: %s", err)
  290. if errors.Is(err, gorm.ErrRecordNotFound) {
  291. return global.UpdateNotFoundOrNoPermissionErr
  292. }
  293. return global.UpdateFailedErr
  294. }
  295. c.Generate(&waybillModel)
  296. err = tx.Save(&waybillModel).Error
  297. if err != nil {
  298. e.Log.Errorf("db error: %s", err)
  299. return global.UpdateFailedErr
  300. }
  301. c.Id = waybillModel.Id
  302. return nil
  303. }
  304. func (e *Waybill) UpdateStatus(c *dto.WaybillUpdateStatusReq, p *actions.DataPermission) error {
  305. var err error
  306. tx := e.Orm.Begin()
  307. defer func() {
  308. if err != nil {
  309. tx.Rollback()
  310. } else {
  311. tx.Commit()
  312. }
  313. }()
  314. var waybillModel = model.Waybill{}
  315. // 查询运单是否存在
  316. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  317. First(&waybillModel, c.GetId()).Error
  318. if err != nil {
  319. e.Log.Errorf("db error: %s", err)
  320. if errors.Is(err, gorm.ErrRecordNotFound) {
  321. return global.UpdateNotFoundOrNoPermissionErr
  322. }
  323. return global.UpdateFailedErr
  324. }
  325. c.Generate(&waybillModel)
  326. err = tx.Save(&waybillModel).Error
  327. if err != nil {
  328. e.Log.Errorf("db error: %s", err)
  329. return global.UpdateFailedErr
  330. }
  331. c.Id = waybillModel.Id
  332. return nil
  333. }
  334. // 派单
  335. func (e *Waybill) Delivery(c *dto.WaybillDeliveryReq, p *actions.DataPermission) error {
  336. var err error
  337. tx := e.Orm.Begin()
  338. defer func() {
  339. if err != nil {
  340. tx.Rollback()
  341. } else {
  342. tx.Commit()
  343. }
  344. }()
  345. if !lib.StrListEqual(c.IceRaftCode, c.OldIceRaftCode) {
  346. // 获取删除的冰排列表
  347. //missingIceRaftCode = lib.FindStrListMissingData(c.OldIceRaftCode, c.IceRaftCode)
  348. //if len(missingIceRaftCode) > 0 {
  349. // // 删除冰排出库记录
  350. // IceRaftList := []model.IceRaft{}
  351. // err = tx.Model(&model.IceRaft{}).Where("code in (?)", missingIceRaftCode).Find(&IceRaftList).Error
  352. // if err != nil {
  353. // e.Log.Errorf("db error: %s", err)
  354. // return errors.New("获取冰排列表失败")
  355. // }
  356. // for _, iceRaft := range IceRaftList {
  357. // // 获取冰排记录
  358. // err = tx.Model(&model.IceRaftRecord{}).
  359. // Where("ice_raft_id = ? and status = ?", iceRaft.Id, model.IceRaftRecordStatusUsing).
  360. // Updates(map[string]interface{}{
  361. // "status": model.IceRaftRecordStatusWaitUse,
  362. // "out_storage_time": nil,
  363. // "cooler_box_id": 0,
  364. // }).Error
  365. // if err != nil {
  366. // e.Log.Errorf("db error: %s", err)
  367. // return errors.New(fmt.Sprintf("冰排【%s】返库失败", iceRaft.Code))
  368. // }
  369. // }
  370. //}
  371. // 获取新增的冰排列表
  372. extraData := lib.FindStrListExtraData(c.OldIceRaftCode, c.IceRaftCode)
  373. if len(extraData) > 0 {
  374. for _, code := range extraData {
  375. var iceRaft model.IceRaft
  376. err = tx.Model(&model.IceRaft{}).Where("code = ?", code).Preload("IceRaftRecord").First(&iceRaft).Error
  377. if err != nil {
  378. e.Log.Errorf("db error: %s", err)
  379. if errors.Is(err, gorm.ErrRecordNotFound) {
  380. return errors.New(fmt.Sprintf("冰排【%s】不存在", code))
  381. } else {
  382. return errors.New(fmt.Sprintf("获取冰排【%s】信息失败", code))
  383. }
  384. }
  385. if iceRaft.IceRaftRecord.Status != model.IceRaftRecordStatusWaitUse {
  386. err = errors.New(fmt.Sprintf("冰排【%s】状态为%s,出库保温箱失败!", code, model.GetIceRaftRecordStatus(iceRaft.IceRaftRecord.Status)))
  387. return err
  388. }
  389. // 获取冰排记录
  390. err = tx.Model(&model.IceRaftRecord{}).
  391. Where("ice_raft_id = ? and status = ?", iceRaft.Id, model.IceRaftRecordStatusWaitUse).
  392. Updates(map[string]interface{}{
  393. "status": model.IceRaftRecordStatusUsing,
  394. "out_storage_time": time.Now(),
  395. "cooler_box_id": c.CoolerBoxId,
  396. }).Error
  397. if err != nil {
  398. e.Log.Errorf("db error: %s", err)
  399. return errors.New(fmt.Sprintf("冰排【%s】出库失败", iceRaft.Code))
  400. }
  401. }
  402. }
  403. }
  404. var coolerBox = model.CoolerBox{}
  405. // 查询保温箱信息
  406. err = tx.Scopes(actions.Permission(coolerBox.TableName(), p)).
  407. First(&coolerBox, c.CoolerBoxId).Error
  408. if err != nil {
  409. e.Log.Errorf("db error: %s", err)
  410. return errors.New("获取保温箱信息失败")
  411. }
  412. for _, id := range c.WaybillIds {
  413. var waybillModel = model.Waybill{}
  414. // 查询运单是否存在
  415. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  416. First(&waybillModel, id).Error
  417. if err != nil {
  418. e.Log.Errorf("db error: %s", err)
  419. if errors.Is(err, gorm.ErrRecordNotFound) {
  420. return global.UpdateNotFoundOrNoPermissionErr
  421. }
  422. return global.UpdateFailedErr
  423. }
  424. waybillModeStatus := waybillModel.Status
  425. if waybillModel.Status == model.WaybillStatusWaitDelivery ||
  426. (waybillModel.Status == model.WaybillStatusInDelivery && waybillModel.CoolerBoxId != c.CoolerBoxId) ||
  427. (waybillModel.Status == model.WaybillStatusInDelivery && !lib.StrListEqual(c.IceRaftCode, c.OldIceRaftCode)) {
  428. waybillModel.Status = model.WaybillStatusInDelivery
  429. waybillModel.CoolerBoxId = c.CoolerBoxId
  430. waybillModel.DeliveryTime = model2.Time(time.Now())
  431. waybillModel.IceRaftCode = c.IceRaftCode
  432. err = tx.Save(&waybillModel).Error
  433. if err != nil {
  434. e.Log.Errorf("db error: %s", err)
  435. return global.UpdateFailedErr
  436. }
  437. // 查询任务
  438. var logistics model.WaybillLogistics
  439. err = tx.Model(&logistics).Where("waybill_no = ? and status = ?", waybillModel.WaybillNo, model.WaybillStatusInDelivery).
  440. Last(&logistics).Error
  441. if err != nil {
  442. if errors.Is(err, gorm.ErrRecordNotFound) {
  443. // 添加物流
  444. logisticsObj := model.WaybillLogistics{
  445. WaybillNo: waybillModel.WaybillNo,
  446. Status: waybillModel.Status,
  447. CoolerBoxId: coolerBox.Id,
  448. ControlBy: model2.ControlBy{
  449. CreateBy: p.UserId,
  450. },
  451. DeptBy: model2.DeptBy{
  452. DeptId: p.DeptId,
  453. },
  454. }
  455. err = tx.Create(&logisticsObj).Error
  456. if err != nil {
  457. e.Log.Errorf("db error: %s", err)
  458. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  459. }
  460. } else {
  461. e.Log.Errorf("db error: %s", err)
  462. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  463. }
  464. }
  465. logistics.CoolerBoxId = coolerBox.Id
  466. err = tx.Save(&logistics).Error
  467. if err != nil {
  468. e.Log.Errorf("db error: %s", err)
  469. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  470. }
  471. // 查询任务
  472. var task model.WaybillTask
  473. err = tx.Model(&task).Where("waybill_no = ? ", waybillModel.WaybillNo).
  474. Last(&task).Error
  475. if err != nil {
  476. if errors.Is(err, gorm.ErrRecordNotFound) {
  477. // 添加任务
  478. taskObj := model.WaybillTask{
  479. WaybillNo: waybillModel.WaybillNo,
  480. CoolerBoxId: coolerBox.Id,
  481. UserId: p.UserId,
  482. Sn: coolerBox.Sn,
  483. StartTime: model2.Time(time.Now()),
  484. ControlBy: model2.ControlBy{
  485. CreateBy: p.UserId,
  486. },
  487. DeptBy: model2.DeptBy{
  488. DeptId: p.DeptId,
  489. },
  490. }
  491. err = tx.Create(&taskObj).Error
  492. if err != nil {
  493. e.Log.Errorf("db error: %s", err)
  494. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  495. }
  496. } else {
  497. e.Log.Errorf("db error: %s", err)
  498. return errors.New(fmt.Sprintf("查询运单任务信息失败:%s", err))
  499. }
  500. }
  501. task.StartTime = model2.Time(time.Now())
  502. task.UpdateBy = p.UserId
  503. task.CoolerBoxId = coolerBox.Id
  504. task.Sn = coolerBox.Sn
  505. err = tx.Save(&task).Error
  506. if err != nil {
  507. e.Log.Errorf("db error: %s", err)
  508. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  509. }
  510. }
  511. // 待派单状态下才发送短信
  512. if waybillModeStatus == model.WaybillStatusWaitDelivery {
  513. ss := sms.NewSMS(conf.ExtConfig.SubMail.Appid, conf.ExtConfig.SubMail.Signature)
  514. addr := conf.ExtConfig.Applet.WaybillUrl + url.QueryEscape(lib.AesEncryptCBC(waybillModel.WaybillNo, lib.AesKey))
  515. res, err1 := ss.SmsXSend(waybillModel.ConsigneeAddressPhone, addr)
  516. if err1 != nil || res.Status != sms.SUCCESS {
  517. e.Log.Errorf("派单短信发送失败", zap.Any("res", res), zap.Error(err1))
  518. err = errors.New("派单短信发送失败,请检查收件人电话是否正确!")
  519. return err
  520. }
  521. waybillModel.SendLog = model.WaybillSendLog{
  522. Phone: waybillModel.ConsigneeAddressPhone,
  523. Content: "【冷链送药追溯平台】您的运单正在派送中,点击查看详情:" + addr,
  524. }
  525. }
  526. }
  527. return nil
  528. }
  529. // Remove 删除Waybill
  530. func (e *Waybill) Remove(c *dto.WaybillDeleteReq, p *actions.DataPermission) error {
  531. var err error
  532. tx := e.Orm.Begin()
  533. defer func() {
  534. if err != nil {
  535. tx.Rollback()
  536. } else {
  537. tx.Commit()
  538. }
  539. }()
  540. var waybillModel model.Waybill
  541. // 查询运单是否存在
  542. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  543. First(&waybillModel, c.GetId()).Error
  544. if err != nil {
  545. e.Log.Errorf("db error: %s", err)
  546. if errors.Is(err, gorm.ErrRecordNotFound) {
  547. return global.DeleteNotFoundOrNoPermissionErr
  548. }
  549. return global.DeleteFailedErr
  550. }
  551. if waybillModel.Status != model.WaybillStatusWaitDelivery {
  552. return errors.New(fmt.Sprintf("运单状态为%s,禁止删除", model.WaybillStatusMap[waybillModel.Status]))
  553. }
  554. db := tx.Delete(&waybillModel)
  555. if err = db.Error; err != nil {
  556. e.Log.Errorf("db error: %s", err)
  557. return global.DeleteFailedErr
  558. }
  559. if db.RowsAffected == 0 {
  560. return global.DeleteNotFoundOrNoPermissionErr
  561. }
  562. return nil
  563. }
  564. func (e *Waybill) Receipt(c *dto.WaybillReceiptReq, p *actions.DataPermission) error {
  565. var err error
  566. tx := e.Orm.Begin()
  567. defer func() {
  568. if err != nil {
  569. tx.Rollback()
  570. } else {
  571. tx.Commit()
  572. }
  573. }()
  574. var waybillModel = model.Waybill{}
  575. // 查询运单是否存在
  576. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  577. Where("waybill_no = ?", c.WaybillNo).
  578. First(&waybillModel).Error
  579. if err != nil {
  580. e.Log.Errorf("db error: %s", err)
  581. if errors.Is(err, gorm.ErrRecordNotFound) {
  582. return errors.New(fmt.Sprintf("运单号%s不存在", c.WaybillNo))
  583. }
  584. return errors.New(fmt.Sprintf("运单号%s查询失败", c.WaybillNo))
  585. }
  586. // 查询保温箱信息
  587. var coolerBox = model.CoolerBox{}
  588. err = tx.Scopes(actions.Permission(coolerBox.TableName(), p)).
  589. First(&coolerBox, waybillModel.CoolerBoxId).Error
  590. if err != nil {
  591. e.Log.Errorf("db error: %s", err)
  592. return errors.New("获取保温箱信息失败")
  593. }
  594. if waybillModel.Status == model.WaybillStatusWaitDelivery {
  595. err = errors.New(fmt.Sprintf("运单状态为%s,禁止操作", model.WaybillStatusMap[waybillModel.Status]))
  596. return err
  597. }
  598. if waybillModel.Status == model.WaybillStatusReceipt || waybillModel.Status == model.WaybillStatusRejection {
  599. return nil
  600. }
  601. waybillModel.Status = c.Status
  602. waybillModel.RejectionReason = c.RejectionReason
  603. waybillModel.ReceiptTime = model2.Time(time.Now())
  604. waybillModel.ReceiptImg = c.ReceiptImg
  605. waybillModel.AssessContent = c.AssessContent
  606. waybillModel.AssessStar = c.AssessStar
  607. waybillModel.DeliveryDuration = int(time.Now().Sub(waybillModel.DeliveryTime.Local()).Minutes())
  608. err = tx.Save(&waybillModel).Error
  609. if err != nil {
  610. e.Log.Errorf("db error: %s", err)
  611. return errors.New(fmt.Sprintf("保存运单信息失败:%s", err))
  612. }
  613. var lng, lat string
  614. lng, lat, err = e.GetSite(waybillModel.DeptId, coolerBox.Sn, waybillModel.ReceiptTime.String())
  615. if err != nil {
  616. e.Log.Errorf("获取定位信息失败: %s", err)
  617. return err
  618. }
  619. // 查询任务
  620. var task model.WaybillTask
  621. err = tx.Model(&task).Where("waybill_no = ? and cooler_box_id = ?", c.WaybillNo, coolerBox.Id).
  622. Last(&task).Error
  623. if err != nil {
  624. e.Log.Errorf("db error: %s", err)
  625. return errors.New(fmt.Sprintf("查询运单任务信息失败:%s", err))
  626. }
  627. // 未下车 直接点签收
  628. if time.Time(task.EndTime).IsZero() {
  629. task.EndTime = model2.Time(time.Now())
  630. //task.UpdateBy = p.UserIds
  631. err = tx.Save(&task).Error
  632. if err != nil {
  633. e.Log.Errorf("db error: %s", err)
  634. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  635. }
  636. }
  637. var userId int
  638. if p != nil {
  639. userId = p.UserId
  640. }
  641. // 添加签收记录
  642. Logistics := model.WaybillLogistics{
  643. WaybillNo: c.WaybillNo,
  644. Status: c.Status,
  645. CoolerBoxId: coolerBox.Id,
  646. UserId: userId,
  647. Lng: lng,
  648. Lat: lat,
  649. ControlBy: model2.ControlBy{
  650. CreateBy: userId,
  651. },
  652. DeptBy: model2.DeptBy{
  653. DeptId: waybillModel.DeptId,
  654. },
  655. ModelTime: model2.ModelTime{
  656. CreatedAt: waybillModel.ReceiptTime,
  657. },
  658. }
  659. err = tx.Create(&Logistics).Error
  660. if err != nil {
  661. e.Log.Errorf("db error: %s", err)
  662. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  663. }
  664. return nil
  665. }
  666. // 获取入库 出库 上车 下车 定位信息
  667. func (e *Waybill) GetSite(companyId int, sn string, time string) (lng, lat string, err error) {
  668. // 获取公司秘钥
  669. var company model.SysDept
  670. company, err = model.GetCompanyById(companyId)
  671. if err != nil {
  672. e.Log.Errorf("db error: %s", err)
  673. return lng, lat, model.GetCompanyKeyErr
  674. }
  675. // 获取传感器信息
  676. var deviceSensorList = []nats_server.DeviceSensor_R{}
  677. var count int64
  678. deviceSensorList, count, err = nats_server.Cold_CompanyDeviceSensor_List_ByKey(sn, company.ColdKey)
  679. if err != nil || count == 0 {
  680. err = errors.New("查询设备定位信息失败")
  681. return lng, lat, err
  682. }
  683. var deviceData nats_server.DeviceData_
  684. deviceData, err = nats_server.Cold_ReadDeviceDataBy_T_snid_T_time(deviceSensorList[0].T_sn, deviceSensorList[0].T_id, time)
  685. if err != nil {
  686. err = errors.New("查询设备定位信息失败")
  687. return lng, lat, err
  688. }
  689. if len(deviceData.T_site) > 0 {
  690. site := strings.Split(deviceSensorList[0].T_DeviceSensorData.T_site, ",")
  691. if len(site) == 2 {
  692. lng = site[0]
  693. lat = site[1]
  694. }
  695. }
  696. return lng, lat, nil
  697. }
  698. // 获取今日运单数 未派单 未装车 未入库 运送中
  699. // 本月运单总数 上月运单总数 本年运单总数 上年运单总数
  700. func (e *Waybill) GetBasicsStats(c *dto.WaybillStatsReq, p *actions.DataPermission) dto.WaybillStatsRes {
  701. var res dto.WaybillStatsRes
  702. var data model.Waybill
  703. type DateCount struct {
  704. Date string
  705. Count int64
  706. }
  707. yearCount := make([]DateCount, 0)
  708. monthCount := make([]DateCount, 0)
  709. now := time.Now()
  710. todayStartTime := now.Format("2006-01-02") + " 00:00:00"
  711. todayEndTime := now.Format("2006-01-02") + " 23:59:59"
  712. // 获取上个月第一天
  713. firstDayOfLastMonth := time.Date(now.Year(), now.Month()-1, 1, 0, 0, 0, 0, now.Location())
  714. // 获取去年的第一天
  715. firstDayOfLastYear := time.Date(now.Year()-1, time.January, 1, 0, 0, 0, 0, now.Location())
  716. monthStartTime := firstDayOfLastMonth.Format("2006-01-02") + " 00:00:00"
  717. yearStartTime := firstDayOfLastYear.Format("2006-01-02") + " 00:00:00"
  718. // 今日总运单数
  719. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("order_time between ? and ?", todayStartTime, todayEndTime).Count(&res.TodayNum)
  720. // 待派单
  721. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusWaitDelivery).Count(&res.WaitDeliveryNum)
  722. // 配送中
  723. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusInDelivery).Count(&res.InDeliveryNum)
  724. // 已送达
  725. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusReceipt).Count(&res.ReceiptNum)
  726. // 已取消
  727. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusRejection).Count(&res.RejectionNum)
  728. // 获取本月,上月数据
  729. e.Orm.Model(&data).Select("date_format(order_time,'%Y%m') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p)).
  730. Where("order_time between ? and ?", monthStartTime, now).Group("date").Find(&monthCount)
  731. for _, month := range monthCount {
  732. if month.Date == now.Format("200601") {
  733. res.ThisMonthNum = month.Count
  734. }
  735. if month.Date == firstDayOfLastMonth.Format("200601") {
  736. res.LastMonthNum = month.Count
  737. }
  738. }
  739. // 获取本年,上年数据
  740. e.Orm.Model(&data).Select("date_format(order_time,'%Y') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p)).
  741. Where("order_time between ? and ?", yearStartTime, now).Group("date").Find(&yearCount)
  742. for _, month := range yearCount {
  743. if month.Date == now.Format("2006") {
  744. res.ThisYearNum = month.Count
  745. }
  746. if month.Date == firstDayOfLastYear.Format("2006") {
  747. res.LastYearNum = month.Count
  748. }
  749. }
  750. if c.Type == "year" {
  751. // 获取上个月第一天
  752. year, _ := strconv.Atoi(c.Date)
  753. firstDayOfyear := time.Date(year, 1, 1, 0, 0, 0, 0, now.Location())
  754. lastDayOfyear := time.Date(year, 12, 31, 23, 59, 59, 0, now.Location())
  755. // 年度数据统计
  756. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p)).
  757. Where("order_time between ? and ?", firstDayOfyear, lastDayOfyear).Group("date").Find(&res.Stats)
  758. }
  759. if c.Type == "month" {
  760. // 获取上个月第一天
  761. month, _ := time.ParseInLocation("2006-01", c.Date, time.Local)
  762. firstDayOfMonth := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, now.Location())
  763. lastDayOfMonth := time.Date(month.Year(), month.Month()+1, 1, 23, 59, 59, 0, now.Location()).Add(-time.Hour * 24)
  764. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m-%d') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p)).
  765. Where("order_time between ? and ?", firstDayOfMonth, lastDayOfMonth).Group("date").Find(&res.Stats)
  766. }
  767. return res
  768. }
  769. func GetDeliveryStatsScopes(userId int) func(db *gorm.DB) *gorm.DB {
  770. return func(db *gorm.DB) *gorm.DB {
  771. if userId == 0 {
  772. return db
  773. }
  774. return db.Where("delivery_id = ?", userId)
  775. }
  776. }
  777. func GetReCheckStatsScopes(userId int) func(db *gorm.DB) *gorm.DB {
  778. return func(db *gorm.DB) *gorm.DB {
  779. if userId == 0 {
  780. return db
  781. }
  782. return db.Where("re_check_id = ?", userId)
  783. }
  784. }
  785. // 获取配送员统计信息
  786. func (e *Waybill) GetDeliveryStats(c *dto.WaybillUserStatsReq, p *actions.DataPermission) (res []dto.WaybillUserStats) {
  787. // 获取用户列表
  788. var userList []model.SysUser
  789. if err := e.Orm.Model(&userList).Scopes(actions.Permission(model.SysUser{}.TableName(), p), WaybillUserStatsUserIdScopes(c.UserIds)).
  790. Where("status = 2").Order("created_at desc").Find(&userList).Error; err != nil {
  791. return nil
  792. }
  793. for _, user := range userList {
  794. stats := e.GetUserStats(c, p, GetDeliveryStatsScopes(user.Id))
  795. stats.Name = user.NickName
  796. res = append(res, stats)
  797. }
  798. return
  799. }
  800. func (e *Waybill) GetReCheckStats(c *dto.WaybillUserStatsReq, p *actions.DataPermission) (res []dto.WaybillUserStats) {
  801. // 获取用户列表
  802. var userList []model.SysUser
  803. if err := e.Orm.Model(&userList).Scopes(actions.Permission(model.SysUser{}.TableName(), p), WaybillUserStatsUserIdScopes(c.UserIds)).
  804. Where("status = 2").Order("created_at desc").Find(&userList).Error; err != nil {
  805. return nil
  806. }
  807. for _, user := range userList {
  808. stats := e.GetUserStats(c, p, GetReCheckStatsScopes(user.Id))
  809. stats.Name = user.NickName
  810. res = append(res, stats)
  811. }
  812. return
  813. }
  814. func WaybillUserStatsUserIdScopes(userIds []int) func(db *gorm.DB) *gorm.DB {
  815. return func(db *gorm.DB) *gorm.DB {
  816. if len(userIds) == 0 {
  817. return db
  818. }
  819. if len(userIds) == 1 {
  820. return db.Where("id = ?", userIds[0])
  821. }
  822. return db.Where("id in (?)", userIds)
  823. }
  824. }
  825. func GetUserBasicsStatsScopes(userId int) func(db *gorm.DB) *gorm.DB {
  826. return func(db *gorm.DB) *gorm.DB {
  827. if userId == 0 {
  828. return db
  829. }
  830. return db.Where("delivery_id = ? or re_check_id = ? or create_by = ?", userId, userId, userId)
  831. }
  832. }
  833. func (e *Waybill) GetUserBasicsStats(c *dto.WaybillStatsReq, p *actions.DataPermission, scopes func(*gorm.DB) *gorm.DB) dto.WaybillStatsRes {
  834. var res dto.WaybillStatsRes
  835. var data model.Waybill
  836. type DateCount struct {
  837. Date string
  838. Count int64
  839. }
  840. yearCount := make([]DateCount, 0)
  841. monthCount := make([]DateCount, 0)
  842. now := time.Now()
  843. todayStartTime := now.Format("2006-01-02") + " 00:00:00"
  844. todayEndTime := now.Format("2006-01-02") + " 23:59:59"
  845. // 获取上个月第一天
  846. firstDayOfLastMonth := time.Date(now.Year(), now.Month()-1, 1, 0, 0, 0, 0, now.Location())
  847. // 获取去年的第一天
  848. firstDayOfLastYear := time.Date(now.Year()-1, time.January, 1, 0, 0, 0, 0, now.Location())
  849. monthStartTime := firstDayOfLastMonth.Format("2006-01-02") + " 00:00:00"
  850. yearStartTime := firstDayOfLastYear.Format("2006-01-02") + " 00:00:00"
  851. // 今日总运单数
  852. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  853. Where("order_time between ? and ?", todayStartTime, todayEndTime).Count(&res.TodayNum)
  854. // 待派单
  855. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  856. Where("status = ?", model.WaybillStatusWaitDelivery).Count(&res.WaitDeliveryNum)
  857. // 配送中
  858. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  859. Where("status = ?", model.WaybillStatusInDelivery).Count(&res.InDeliveryNum)
  860. // 已送达
  861. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  862. Where("status = ?", model.WaybillStatusReceipt).Count(&res.ReceiptNum)
  863. // 已取消
  864. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  865. Where("status = ?", model.WaybillStatusRejection).Count(&res.RejectionNum)
  866. // 获取本月,上月数据
  867. e.Orm.Model(&data).Select("date_format(order_time,'%Y%m') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p), scopes).
  868. Where("order_time between ? and ?", monthStartTime, now).Group("date").Find(&monthCount)
  869. for _, month := range monthCount {
  870. if month.Date == now.Format("200601") {
  871. res.ThisMonthNum = month.Count
  872. }
  873. if month.Date == firstDayOfLastMonth.Format("200601") {
  874. res.LastMonthNum = month.Count
  875. }
  876. }
  877. // 获取本年,上年数据
  878. e.Orm.Model(&data).Select("date_format(order_time,'%Y') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p), scopes).
  879. Where("order_time between ? and ?", yearStartTime, now).Group("date").Find(&yearCount)
  880. for _, month := range yearCount {
  881. if month.Date == now.Format("2006") {
  882. res.ThisYearNum = month.Count
  883. }
  884. if month.Date == firstDayOfLastYear.Format("2006") {
  885. res.LastYearNum = month.Count
  886. }
  887. }
  888. if c.Type == "year" {
  889. // 获取上个月第一天
  890. year, _ := strconv.Atoi(c.Date)
  891. firstDayOfyear := time.Date(year, 1, 1, 0, 0, 0, 0, now.Location())
  892. lastDayOfyear := time.Date(year, 12, 31, 23, 59, 59, 0, now.Location())
  893. // 年度数据统计
  894. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p), scopes).
  895. Where("order_time between ? and ?", firstDayOfyear, lastDayOfyear).Group("date").Find(&res.Stats)
  896. }
  897. if c.Type == "month" {
  898. // 获取上个月第一天
  899. month, _ := time.ParseInLocation("2006-01", c.Date, time.Local)
  900. firstDayOfMonth := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, now.Location())
  901. lastDayOfMonth := time.Date(month.Year(), month.Month()+1, 1, 23, 59, 59, 0, now.Location()).Add(-time.Hour * 24)
  902. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m-%d') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p), scopes).
  903. Where("order_time between ? and ?", firstDayOfMonth, lastDayOfMonth).Group("date").Find(&res.Stats)
  904. }
  905. return res
  906. }
  907. func (e *Waybill) GetUserStats(c *dto.WaybillUserStatsReq, p *actions.DataPermission, scopes func(*gorm.DB) *gorm.DB) dto.WaybillUserStats {
  908. var res dto.WaybillUserStats
  909. var data model.Waybill
  910. type DateCount struct {
  911. Date string
  912. Count int64
  913. }
  914. now := time.Now()
  915. if c.Type == "year" {
  916. // 获取上个月第一天
  917. year, _ := strconv.Atoi(c.Date)
  918. firstDayOfyear := time.Date(year, 1, 1, 0, 0, 0, 0, now.Location())
  919. lastDayOfyear := time.Date(year, 12, 31, 23, 59, 59, 0, now.Location())
  920. // 年度数据统计
  921. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p), scopes).
  922. Where("order_time between ? and ?", firstDayOfyear, lastDayOfyear).Group("date").Find(&res.Stats)
  923. // 获取这个月的所有日期
  924. allDates := getAllDatesInYear(c.Date)
  925. // 补齐缺失日期的数据
  926. res.Stats = completeMissingDates(allDates, res.Stats)
  927. }
  928. if c.Type == "month" {
  929. // 获取上个月第一天
  930. month, _ := time.ParseInLocation("2006-01", c.Date, time.Local)
  931. firstDayOfMonth := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, now.Location())
  932. lastDayOfMonth := time.Date(month.Year(), month.Month()+1, 1, 23, 59, 59, 0, now.Location()).Add(-time.Hour * 24)
  933. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m-%d') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p), scopes).
  934. Where("order_time between ? and ?", firstDayOfMonth, lastDayOfMonth).Group("date").Find(&res.Stats)
  935. // 获取这个月的所有日期
  936. allDates := getAllDatesInMonth(c.Date)
  937. // 补齐缺失日期的数据
  938. res.Stats = completeMissingDates(allDates, res.Stats)
  939. }
  940. return res
  941. }
  942. // 获取指定月份的所有日期
  943. func getAllDatesInMonth(month string) []string {
  944. var dates []string
  945. layout := "2006-01-02"
  946. firstDay, _ := time.Parse(layout, month+"-01")
  947. if time.Now().Before(firstDay) {
  948. return dates
  949. }
  950. lastDay := firstDay.AddDate(0, 1, -1)
  951. if time.Now().Before(lastDay) {
  952. lastDay = time.Now()
  953. }
  954. for d := firstDay; !d.After(lastDay); d = d.AddDate(0, 0, 1) {
  955. dates = append(dates, d.Format(layout))
  956. }
  957. return dates
  958. }
  959. // 获取指定年份的所有日期
  960. func getAllDatesInYear(year string) []string {
  961. var dates []string
  962. layout := "2006-01"
  963. firstDay, _ := time.Parse(layout, year+"-01")
  964. lastDay := firstDay.AddDate(1, 0, -1)
  965. if time.Now().Before(firstDay) {
  966. return dates
  967. }
  968. if time.Now().Before(lastDay) {
  969. lastDay = time.Now()
  970. }
  971. for d := firstDay; !d.After(lastDay); d = d.AddDate(0, 1, 0) {
  972. dates = append(dates, d.Format(layout))
  973. }
  974. return dates
  975. }
  976. // 补齐缺失日期的数据
  977. func completeMissingDates(allDates []string, stats []dto.WaybillStats) []dto.WaybillStats {
  978. dateMap := make(map[string]int64)
  979. for _, stat := range stats {
  980. dateMap[stat.Date] = stat.Num
  981. }
  982. var completedStats []dto.WaybillStats
  983. for _, date := range allDates {
  984. num, exists := dateMap[date]
  985. if !exists {
  986. num = 0
  987. }
  988. completedStats = append(completedStats, dto.WaybillStats{Date: date, Num: num})
  989. }
  990. return completedStats
  991. }
  992. // 获取运单所有温湿度素具
  993. func (e *Waybill) GetAllData(c *dto.WaybillGetByWaybillNoReq) ([]nats_server.DeviceData_R, []WaybillPDF, error) {
  994. var err error
  995. var data model.WaybillTask
  996. var waybill model.Waybill
  997. var taskList []model.WaybillTask
  998. var waybillPDF []WaybillPDF
  999. dataList := make([]nats_server.DeviceData_R, 0)
  1000. err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
  1001. if err != nil {
  1002. e.Log.Errorf("db error: %s", err)
  1003. return dataList, waybillPDF, errors.New("获取运单信息失败")
  1004. }
  1005. // 未签收,不返回数据
  1006. if waybill.Status != model.WaybillStatusReceipt {
  1007. return dataList, waybillPDF, nil
  1008. }
  1009. // 获取公司秘钥
  1010. var company model.SysDept
  1011. company, err = model.GetCompanyById(waybill.DeptId)
  1012. if err != nil {
  1013. e.Log.Errorf("db error: %s", err)
  1014. return dataList, waybillPDF, model.GetCompanyKeyErr
  1015. }
  1016. err = e.Orm.Model(&data).
  1017. Where("waybill_no = ?", c.WaybillNo).
  1018. Order("id desc").
  1019. Find(&taskList).Error
  1020. if err != nil {
  1021. e.Log.Errorf("db error: %s", err)
  1022. return dataList, waybillPDF, global.GetFailedErr
  1023. }
  1024. // 获取最后一个任务id
  1025. var lastWaybillTask model.WaybillTask
  1026. err = e.Orm.Model(&lastWaybillTask).Where("waybill_no = ?", c.WaybillNo).Last(&lastWaybillTask).Error
  1027. if err != nil {
  1028. e.Log.Errorf("db error: %s", err)
  1029. err = errors.New("获取运单信息错误!")
  1030. return dataList, waybillPDF, err
  1031. }
  1032. // 创建名称到权重的映射
  1033. orderMap := make(map[string]int)
  1034. for i, v := range taskList {
  1035. orderMap[v.Sn] = i
  1036. }
  1037. for i := 0; i < len(taskList); i++ {
  1038. // 获取传感器信息
  1039. deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(taskList[i].Sn, company.ColdKey)
  1040. var T_snid string
  1041. var list []nats_server.DeviceData_R
  1042. for _, r := range deviceSensorList {
  1043. T_snid += fmt.Sprintf("%s,%d|", r.T_sn, r.T_id)
  1044. }
  1045. var count int64
  1046. list, count, err = nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, taskList[i].StartTime.String(), taskList[i].EndTime.String(), 0, 9999)
  1047. if err != nil {
  1048. e.Log.Errorf("nats 获取温湿度信息失败: %s", err)
  1049. return dataList, waybillPDF, global.GetFailedErr
  1050. }
  1051. firstMap := map[int]nats_server.DeviceData_R{}
  1052. lastMap := map[int]nats_server.DeviceData_R{}
  1053. if count > 0 {
  1054. for _, v := range deviceSensorList {
  1055. for j := 0; j < len(list); j++ {
  1056. if v.T_id == list[j].T_id {
  1057. if list[j].T_time != taskList[i].StartTime.String() {
  1058. firstData := list[j]
  1059. firstData.T_time = taskList[i].StartTime.String()
  1060. firstMap[v.T_id] = firstData
  1061. count += 1
  1062. }
  1063. break
  1064. }
  1065. }
  1066. if waybill.Status == model.WaybillStatusReceipt {
  1067. for k := len(list) - 1; k >= 0; k-- {
  1068. if v.T_id == list[k].T_id {
  1069. if taskList[i].Id == lastWaybillTask.Id && list[k].T_time != taskList[i].EndTime.String() && !time.Time(taskList[i].EndTime).IsZero() {
  1070. lastData := list[k]
  1071. lastData.T_time = taskList[i].EndTime.String()
  1072. lastMap[v.T_id] = lastData
  1073. count += 1
  1074. }
  1075. break
  1076. }
  1077. }
  1078. }
  1079. }
  1080. }
  1081. for _, v := range firstMap {
  1082. list = append(list, v)
  1083. }
  1084. for _, v := range lastMap {
  1085. list = append(list, v)
  1086. }
  1087. sort.Slice(list, func(x, y int) bool {
  1088. if list[x].T_time == list[y].T_time {
  1089. // 如果时间相同,则按预设顺序排序
  1090. return orderMap[list[x].T_sn] < orderMap[list[y].T_sn]
  1091. }
  1092. return list[x].T_time > list[y].T_time
  1093. })
  1094. dataList = append(dataList, list...)
  1095. waybillPDF = append(waybillPDF, WaybillPDF{
  1096. Data: list,
  1097. DeviceSensorList: deviceSensorList,
  1098. Task: taskList[i],
  1099. })
  1100. }
  1101. sort.Slice(dataList, func(i, j int) bool {
  1102. if dataList[i].T_time == dataList[j].T_time {
  1103. // 如果时间相同,则按预设顺序排序
  1104. return orderMap[dataList[i].T_sn] < orderMap[dataList[j].T_sn]
  1105. }
  1106. return dataList[i].T_time < dataList[j].T_time
  1107. })
  1108. return dataList, waybillPDF, nil
  1109. }
  1110. type WaybillPDF struct {
  1111. Data []nats_server.DeviceData_R `json:"data"`
  1112. DeviceSensorList []nats_server.DeviceSensor_R `json:"deviceSensorList"`
  1113. Task model.WaybillTask `json:"task"`
  1114. }
  1115. // Insert 创建Waybill对象
  1116. func (e *Waybill) InsertByOrderId(c *dto.WeianGetWaybillNoReq) error {
  1117. var err error
  1118. var data model.Waybill
  1119. tx := e.Orm.Begin()
  1120. defer func() {
  1121. if err != nil {
  1122. tx.Rollback()
  1123. } else {
  1124. tx.Commit()
  1125. }
  1126. }()
  1127. var company model.SysDept
  1128. var i int64
  1129. err = e.Orm.Model(&company).Where("name = ?", c.CompanyName).Count(&i).Error
  1130. if err != nil {
  1131. e.Log.Errorf("db error: %s", err)
  1132. return global.CreateFailedErr
  1133. }
  1134. if i == 0 {
  1135. err = errors.New("公司名称不存在!")
  1136. e.Log.Errorf("db error: %s", err)
  1137. return err
  1138. }
  1139. var no string
  1140. for {
  1141. no = time.Now().Format("200601021504") + utils.GetRandString(6, "0123456789", 0)
  1142. var j int64
  1143. err = e.Orm.Model(&data).Where("waybill_no = ?", no).Count(&j).Error
  1144. if err != nil {
  1145. continue
  1146. }
  1147. if j == 0 {
  1148. break
  1149. }
  1150. }
  1151. // 添加运单
  1152. data.WaybillNo = no
  1153. data.OrderNo = c.OrderId
  1154. data.DeptId = company.Id
  1155. data.Status = 1
  1156. data.OrderTime = model2.Time(time.Now())
  1157. err = tx.Create(&data).Error
  1158. if err != nil {
  1159. e.Log.Errorf("db error: %s", err)
  1160. return global.CreateFailedErr
  1161. }
  1162. c.WaybillNo = data.WaybillNo
  1163. return nil
  1164. }