waybill.go 44 KB

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