waybill.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  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. actions.Permission(data.TableName(), p),
  120. orStatus(c.Status),
  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. sole, err := e.CreateSole()
  307. if err != nil {
  308. err = errors.New("生成运单号失败")
  309. return err
  310. }
  311. data.OrderNo = sole
  312. c.Generate(&data)
  313. err = tx.Create(&data).Error
  314. if err != nil {
  315. e.Log.Errorf("db error: %s", err)
  316. return global.CreateFailedErr
  317. }
  318. c.Id = data.Id
  319. // 保存收货地址
  320. //if c.SaveSenderAddress {
  321. // // 查询地址是否存在
  322. // address := model.Address{}
  323. // err = e.Orm.Where("address = ? and phone = ? and name = ? and dept_id = ? and address_type = 'sender'",
  324. // c.SenderAddressDetails, c.SenderAddressPhone, c.SenderAddressName, c.DeptId).First(&address).Error
  325. // if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  326. // address.Address = c.SenderAddressDetails
  327. // address.Phone = c.SenderAddressPhone
  328. // address.Name = c.SenderAddressName
  329. // address.DeptId = c.DeptId
  330. // address.AddressType = "sender"
  331. // err = tx.Create(&address).Error
  332. // if err != nil {
  333. // e.Log.Errorf("创建地址失败: %s", err)
  334. // return global.CreateFailedErr
  335. // }
  336. // }
  337. //}
  338. // 保存发货地址
  339. if c.SaveConsigneeAddress {
  340. // 查询地址是否存在
  341. address := model.Address{}
  342. err = e.Orm.Where("address = ? and phone = ? and name = ? and dept_id = ? and address_type = 'consignee'",
  343. c.ConsigneeAddressDetails, c.ConsigneeAddressPhone, c.ConsigneeAddressName, c.DeptId).First(&address).Error
  344. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  345. address.Address = c.ConsigneeAddressDetails
  346. address.Phone = c.ConsigneeAddressPhone
  347. address.Name = c.ConsigneeAddressName
  348. address.DeptId = c.DeptId
  349. address.AddressType = "consignee"
  350. err = tx.Create(&address).Error
  351. if err != nil {
  352. e.Log.Errorf("创建地址失败: %s", err)
  353. return global.CreateFailedErr
  354. }
  355. }
  356. }
  357. if len(c.Drugs) > 0 {
  358. for _, drug := range c.Drugs {
  359. var drugs model.Drug
  360. drugs.WaybillNo = no
  361. drugs.Drug_ent_base_info_id = drug.Drug_ent_base_info_id
  362. drugs.Ent_name = drug.Ent_name
  363. drugs.Physic_name = drug.Physic_name
  364. drugs.Approval_licence_no = drug.Approval_licence_no
  365. drugs.Prepn_spec = drug.Prepn_spec
  366. drugs.Physic_type_desc = drug.Physic_type_desc
  367. drugs.Pkg_spec_crit = drug.Pkg_spec_crit
  368. drugs.Prepn_type_desc = drug.Prepn_type_desc
  369. drugs.Code = drug.Code
  370. err = tx.Save(&drugs).Error
  371. if err != nil {
  372. e.Log.Errorf("db error: %s", err)
  373. return errors.New("保存药品信息失败")
  374. }
  375. }
  376. }
  377. return nil
  378. }
  379. // Update 修改Waybill对象
  380. func (e *Waybill) Update(c *dto.WaybillUpdateReq, p *actions.DataPermission) error {
  381. var err error
  382. tx := e.Orm.Begin()
  383. defer func() {
  384. if err != nil {
  385. tx.Rollback()
  386. } else {
  387. tx.Commit()
  388. }
  389. }()
  390. var waybillModel = model.Waybill{}
  391. // 查询运单是否存在
  392. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  393. First(&waybillModel, c.GetId()).Error
  394. if err != nil {
  395. e.Log.Errorf("db error: %s", err)
  396. if errors.Is(err, gorm.ErrRecordNotFound) {
  397. return global.UpdateNotFoundOrNoPermissionErr
  398. }
  399. return global.UpdateFailedErr
  400. }
  401. c.Generate(&waybillModel)
  402. err = tx.Save(&waybillModel).Error
  403. if err != nil {
  404. e.Log.Errorf("db error: %s", err)
  405. return global.UpdateFailedErr
  406. }
  407. c.Id = waybillModel.Id
  408. return nil
  409. }
  410. // 审核订单
  411. func (e *Waybill) Audit(c *dto.WaybillUpdateReqaudit, p *actions.DataPermission) error {
  412. var err error
  413. tx := e.Orm.Begin()
  414. defer func() {
  415. if err != nil {
  416. tx.Rollback()
  417. } else {
  418. tx.Commit()
  419. }
  420. }()
  421. var waybillModel = model.Waybill{}
  422. // 查询运单是否存在
  423. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  424. First(&waybillModel, c.GetId()).Error
  425. if err != nil {
  426. e.Log.Errorf("db error: %s", err)
  427. if errors.Is(err, gorm.ErrRecordNotFound) {
  428. return global.UpdateNotFoundOrNoPermissionErr
  429. }
  430. return global.UpdateFailedErr
  431. }
  432. c.Generate(&waybillModel)
  433. waybillModel.Status = c.Status
  434. waybillModel.ReCheckId = p.UserId
  435. err = tx.Updates(&waybillModel).Error
  436. if err != nil {
  437. e.Log.Errorf("db error: %s", err)
  438. return global.UpdateFailedErr
  439. }
  440. c.Id = waybillModel.Id
  441. return nil
  442. }
  443. // 管理员审核订单
  444. func (e *Waybill) AdminAudit(c *dto.WaybillAdmin, p *actions.DataPermission) error {
  445. var err error
  446. tx := e.Orm.Begin()
  447. defer func() {
  448. if err != nil {
  449. tx.Rollback()
  450. } else {
  451. tx.Commit()
  452. }
  453. }()
  454. var waybillModel = model.Waybill{}
  455. // 查询运单是否存在
  456. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  457. First(&waybillModel, c.GetId()).Error
  458. if err != nil {
  459. e.Log.Errorf("db error: %s", err)
  460. if errors.Is(err, gorm.ErrRecordNotFound) {
  461. return global.UpdateNotFoundOrNoPermissionErr
  462. }
  463. return global.UpdateFailedErr
  464. }
  465. c.Generate(&waybillModel)
  466. waybillModel.AdminAuditRemark = c.AdminAuditRemark
  467. err = tx.Updates(&waybillModel).Error
  468. if err != nil {
  469. e.Log.Errorf("db error: %s", err)
  470. return global.UpdateFailedErr
  471. }
  472. c.Id = waybillModel.Id
  473. return nil
  474. }
  475. func (e *Waybill) UpdateStatus(c *dto.UpdateStatusReq, p *actions.DataPermission) error {
  476. var err error
  477. tx := e.Orm.Begin()
  478. defer func() {
  479. if err != nil {
  480. tx.Rollback()
  481. } else {
  482. tx.Commit()
  483. }
  484. }()
  485. // 查询运单是否存在
  486. for _, v := range c.Id {
  487. var waybillModel = model.Waybill{}
  488. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  489. First(&waybillModel, v).Error
  490. if err != nil {
  491. e.Log.Errorf("db error: %s", err)
  492. if errors.Is(err, gorm.ErrRecordNotFound) {
  493. return global.UpdateNotFoundOrNoPermissionErr
  494. }
  495. return global.UpdateFailedErr
  496. }
  497. waybillModel.Status = c.Status
  498. err = tx.Table(waybillModel.TableName()).Where("id=?", v).Update("status", c.Status).Error
  499. if err != nil {
  500. e.Log.Errorf("db error: %s", err)
  501. return global.UpdateFailedErr
  502. }
  503. // 查询任务
  504. //var logistics model.WaybillLogistics
  505. //err = tx.Model(&logistics).Where("waybill_no = ? and status = ?", waybillModel.WaybillNo, model.WaybillStatusInDeliverys).
  506. // Last(&logistics).Error
  507. //if err != nil {
  508. // if errors.Is(err, gorm.ErrRecordNotFound) {
  509. // // 添加物流
  510. // logisticsObj := model.WaybillLogistics{
  511. // WaybillNo: waybillModel.WaybillNo,
  512. // Status: waybillModel.Status,
  513. // ControlBy: model2.ControlBy{
  514. // CreateBy: p.UserId,
  515. // },
  516. // DeptBy: model2.DeptBy{
  517. // DeptId: p.DeptId,
  518. // },
  519. // }
  520. // err = tx.Create(&logisticsObj).Error
  521. // if err != nil {
  522. // e.Log.Errorf("db error: %s", err)
  523. // return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  524. // }
  525. // } else {
  526. // e.Log.Errorf("db error: %s", err)
  527. // return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  528. // }
  529. //}
  530. //err = tx.Save(&logistics).Error
  531. //if err != nil {
  532. // e.Log.Errorf("db error: %s", err)
  533. // return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  534. //}
  535. }
  536. //err = tx.Save(&waybillModel).Error
  537. //if err != nil {
  538. // e.Log.Errorf("db error: %s", err)
  539. // return global.UpdateFailedErr
  540. //}
  541. return nil
  542. }
  543. // 派单
  544. func (e *Waybill) Delivery(c *dto.WaybillDeliveryReq, p *actions.DataPermission) error {
  545. var err error
  546. tx := e.Orm.Begin()
  547. defer func() {
  548. if err != nil {
  549. tx.Rollback()
  550. } else {
  551. tx.Commit()
  552. }
  553. }()
  554. if !lib.StrListEqual(c.IceRaftCode, c.OldIceRaftCode) {
  555. // 获取删除的冰排列表
  556. //missingIceRaftCode = lib.FindStrListMissingData(c.OldIceRaftCode, c.IceRaftCode)
  557. //if len(missingIceRaftCode) > 0 {
  558. // // 删除冰排出库记录
  559. // IceRaftList := []model.IceRaft{}
  560. // err = tx.Model(&model.IceRaft{}).Where("code in (?)", missingIceRaftCode).Find(&IceRaftList).Error
  561. // if err != nil {
  562. // e.Log.Errorf("db error: %s", err)
  563. // return errors.New("获取冰排列表失败")
  564. // }
  565. // for _, iceRaft := range IceRaftList {
  566. // // 获取冰排记录
  567. // err = tx.Model(&model.IceRaftRecord{}).
  568. // Where("ice_raft_id = ? and status = ?", iceRaft.Id, model.IceRaftRecordStatusUsing).
  569. // Updates(map[string]interface{}{
  570. // "status": model.IceRaftRecordStatusWaitUse,
  571. // "out_storage_time": nil,
  572. // "cooler_box_id": 0,
  573. // }).Error
  574. // if err != nil {
  575. // e.Log.Errorf("db error: %s", err)
  576. // return errors.New(fmt.Sprintf("冰排【%s】返库失败", iceRaft.Code))
  577. // }
  578. // }
  579. //}
  580. // 获取新增的冰排列表
  581. extraData := lib.FindStrListExtraData(c.OldIceRaftCode, c.IceRaftCode)
  582. if len(extraData) > 0 {
  583. for _, code := range extraData {
  584. var iceRaft model.IceRaft
  585. err = tx.Model(&model.IceRaft{}).Where("code = ?", code).Preload("IceRaftRecord").First(&iceRaft).Error
  586. if err != nil {
  587. e.Log.Errorf("db error: %s", err)
  588. if errors.Is(err, gorm.ErrRecordNotFound) {
  589. return errors.New(fmt.Sprintf("冰排【%s】不存在", code))
  590. } else {
  591. return errors.New(fmt.Sprintf("获取冰排【%s】信息失败", code))
  592. }
  593. }
  594. if iceRaft.IceRaftRecord.Status != model.IceRaftRecordStatusWaitUse {
  595. err = errors.New(fmt.Sprintf("冰排【%s】状态为%s,出库保温箱失败!", code, model.GetIceRaftRecordStatus(iceRaft.IceRaftRecord.Status)))
  596. return err
  597. }
  598. // 获取冰排记录
  599. err = tx.Model(&model.IceRaftRecord{}).
  600. Where("ice_raft_id = ? and status = ?", iceRaft.Id, model.IceRaftRecordStatusWaitUse).
  601. Updates(map[string]interface{}{
  602. "status": model.IceRaftRecordStatusUsing,
  603. "out_storage_time": time.Now(),
  604. "cooler_box_id": c.CoolerBoxId,
  605. }).Error
  606. if err != nil {
  607. e.Log.Errorf("db error: %s", err)
  608. return errors.New(fmt.Sprintf("冰排【%s】出库失败", iceRaft.Code))
  609. }
  610. }
  611. }
  612. }
  613. var coolerBox = model.CoolerBox{}
  614. // 查询保温箱信息
  615. if c.CoolerBoxId != 0 {
  616. err = tx.Scopes(actions.Permission(coolerBox.TableName(), p)).
  617. First(&coolerBox, c.CoolerBoxId).Error
  618. if err != nil {
  619. e.Log.Errorf("db error: %s", err)
  620. return errors.New("获取保温箱信息失败")
  621. }
  622. }
  623. var user model.SysUser
  624. first := e.Orm.Table(user.TableName()).Where("id = ?", p.UserId).First(&user)
  625. if first.Error != nil {
  626. return global.GetFailedErr
  627. }
  628. for _, id := range c.WaybillIds {
  629. var waybillModel = model.Waybill{}
  630. // 查询运单是否存在
  631. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  632. First(&waybillModel, id).Error
  633. if err != nil {
  634. e.Log.Errorf("db error: %s", err)
  635. if errors.Is(err, gorm.ErrRecordNotFound) {
  636. return global.UpdateNotFoundOrNoPermissionErr
  637. }
  638. return global.UpdateFailedErr
  639. }
  640. //派单时添加
  641. //waybillModeStatus := waybillModel.Status
  642. if waybillModel.Status == model.WaybillStatusInDeliverys ||
  643. (waybillModel.Status == model.WaybillStatusInDeliverys && waybillModel.CoolerBoxId != c.CoolerBoxId) ||
  644. (waybillModel.Status == model.WaybillStatusInDeliverys && !lib.StrListEqual(c.IceRaftCode, c.OldIceRaftCode)) {
  645. waybillModel.Status = model.WaybillStatusInDeliverys
  646. waybillModel.TamperProofLabel = c.TamperProofLabel
  647. waybillModel.TamperProofLabelImg = c.TamperProofLabelImg // 防拆标签
  648. waybillModel.DeliveryId = c.DeliveryId
  649. waybillModel.AssignmentStatus = 2 // 分配状态 2 已派单
  650. waybillModel.CoolerBoxId = c.CoolerBoxId
  651. waybillModel.DeliveryTime = model2.Time(time.Now())
  652. waybillModel.IceRaftCode = c.IceRaftCode
  653. if c.Status == model.WaybillStatusInShippeds {
  654. waybillModel.Status = c.Status
  655. // 查询保温箱信息
  656. var coolerBoxModel model.CoolerBox
  657. err = e.Orm.Scopes(actions.Permission(coolerBoxModel.TableName(), p)).
  658. First(&coolerBoxModel, waybillModel.CoolerBoxId).Error
  659. if err != nil {
  660. e.Log.Errorf("获取保温箱信息失败: %s", err)
  661. return errors.New("获取保温箱信息失败")
  662. }
  663. var data model.IceRaft
  664. var list []string
  665. err := e.Orm.Model(&data).
  666. Select("ice_raft.code").
  667. Scopes(
  668. actions.Permission(data.TableName(), p),
  669. IceRaftNameRecordStatusScopes(model.IceRaftRecordStatusUsing),
  670. IceRaftNameRecordCoolerBoxIdScopes(coolerBoxModel.Id),
  671. ).
  672. Joins("left join ice_raft_record on ice_raft.ice_raft_record_id = ice_raft_record.id").
  673. Find(&list).Error
  674. if err != nil {
  675. e.Log.Errorf("db error: %s", err)
  676. return errors.New("获取冰排编号失败")
  677. }
  678. //查询保温箱记录信息状态为1使用中
  679. var cooler model.CoolerBoxRecord
  680. err = e.Orm.Scopes(actions.Permission(cooler.TableName(), p)).
  681. First(&cooler).Where("cooler_box_id = ?", coolerBoxModel.Id).Where("status = ?", 1).Error
  682. if err != nil {
  683. e.Log.Errorf("db 获取保温箱记录信息失败: %s", err)
  684. return errors.New("获取保温箱记录信息失败")
  685. }
  686. cooler.CoolerUseUsers = user.NickName
  687. cooler.HistoryCode = append(cooler.HistoryCode, list...)
  688. cooler.CoolerUserTime = model2.Time(time.Now())
  689. cooler.Status = "2" //使用结束
  690. err = e.Orm.Updates(&cooler).Where("id = ?", cooler.Id).Error
  691. if err != nil {
  692. e.Log.Errorf("db error: %s", err)
  693. return errors.New("保存保温箱记录失败")
  694. }
  695. // 配送中状态下才发送短信
  696. ss := sms.NewSMS(conf.ExtConfig.SubMail.Appid, conf.ExtConfig.SubMail.Signature)
  697. addr := conf.ExtConfig.Applet.WaybillUrl + url.QueryEscape(lib.AesEncryptCBC(waybillModel.WaybillNo, lib.AesKey))
  698. res, err1 := ss.SmsXSend(waybillModel.ConsigneeAddressPhone, addr)
  699. if err1 != nil || res.Status != sms.SUCCESS {
  700. e.Log.Errorf("派单短信发送失败", zap.Any("res", res), zap.Error(err1))
  701. err = errors.New("派单短信发送失败,请检查收件人电话是否正确!")
  702. return err
  703. }
  704. waybillModel.SendLog = model.WaybillSendLog{
  705. Phone: waybillModel.ConsigneeAddressPhone,
  706. Content: "【冷链送药追溯平台】您的运单正在派送中,点击查看详情:" + addr,
  707. }
  708. // 查询任务
  709. var logistics model.WaybillLogistics
  710. // 添加物流
  711. logisticsObj := model.WaybillLogistics{
  712. WaybillNo: waybillModel.WaybillNo,
  713. Status: waybillModel.Status,
  714. CoolerBoxId: coolerBox.Id,
  715. ControlBy: model2.ControlBy{
  716. CreateBy: p.UserId,
  717. },
  718. DeptBy: model2.DeptBy{
  719. DeptId: p.DeptId,
  720. },
  721. }
  722. err = tx.Create(&logisticsObj).Error
  723. if err != nil {
  724. e.Log.Errorf("db error: %s", err)
  725. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  726. }
  727. logistics.CoolerBoxId = coolerBox.Id
  728. err = tx.Save(&logistics).Error
  729. if err != nil {
  730. e.Log.Errorf("db error: %s", err)
  731. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  732. }
  733. }
  734. err = tx.Save(&waybillModel).Error
  735. if err != nil {
  736. e.Log.Errorf("db error: %s", err)
  737. return global.UpdateFailedErr
  738. }
  739. // 查询任务
  740. var logistics model.WaybillLogistics
  741. err = tx.Model(&logistics).Where("waybill_no = ?", waybillModel.WaybillNo).
  742. Last(&logistics).Error
  743. if err != nil {
  744. if errors.Is(err, gorm.ErrRecordNotFound) {
  745. // 添加物流
  746. logisticsObj := model.WaybillLogistics{
  747. WaybillNo: waybillModel.WaybillNo,
  748. Status: waybillModel.Status,
  749. CoolerBoxId: coolerBox.Id,
  750. ControlBy: model2.ControlBy{
  751. CreateBy: p.UserId,
  752. },
  753. DeptBy: model2.DeptBy{
  754. DeptId: p.DeptId,
  755. },
  756. }
  757. err = tx.Create(&logisticsObj).Error
  758. if err != nil {
  759. e.Log.Errorf("db error: %s", err)
  760. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  761. }
  762. } else {
  763. e.Log.Errorf("db error: %s", err)
  764. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  765. }
  766. logistics.CoolerBoxId = coolerBox.Id
  767. err = tx.Save(&logistics).Error
  768. if err != nil {
  769. e.Log.Errorf("db error: %s", err)
  770. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  771. }
  772. }
  773. // 查询任务
  774. var task model.WaybillTask
  775. err = tx.Model(&task).Where("waybill_no = ? ", waybillModel.WaybillNo).
  776. Last(&task).Error
  777. if err != nil {
  778. if errors.Is(err, gorm.ErrRecordNotFound) {
  779. // 添加任务
  780. taskObj := model.WaybillTask{
  781. WaybillNo: waybillModel.WaybillNo,
  782. CoolerBoxId: coolerBox.Id,
  783. UserId: p.UserId,
  784. Sn: coolerBox.Sn,
  785. StartTime: model2.Time(time.Now()),
  786. ControlBy: model2.ControlBy{
  787. CreateBy: p.UserId,
  788. },
  789. DeptBy: model2.DeptBy{
  790. DeptId: p.DeptId,
  791. },
  792. }
  793. err = tx.Create(&taskObj).Error
  794. if err != nil {
  795. e.Log.Errorf("db error: %s", err)
  796. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  797. }
  798. } else {
  799. e.Log.Errorf("db error: %s", err)
  800. return errors.New(fmt.Sprintf("查询运单任务信息失败:%s", err))
  801. }
  802. task.StartTime = model2.Time(time.Now())
  803. task.UpdateBy = p.UserId
  804. task.CoolerBoxId = coolerBox.Id
  805. task.Sn = coolerBox.Sn
  806. err = tx.Save(&task).Error
  807. if err != nil {
  808. e.Log.Errorf("db error: %s", err)
  809. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  810. }
  811. }
  812. }
  813. }
  814. return nil
  815. }
  816. // Remove 删除Waybill
  817. func (e *Waybill) Remove(c *dto.WaybillDeleteReq, p *actions.DataPermission) error {
  818. var err error
  819. tx := e.Orm.Begin()
  820. defer func() {
  821. if err != nil {
  822. tx.Rollback()
  823. } else {
  824. tx.Commit()
  825. }
  826. }()
  827. var waybillModel model.Waybill
  828. // 查询运单是否存在
  829. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  830. First(&waybillModel, c.GetId()).Error
  831. if err != nil {
  832. e.Log.Errorf("db error: %s", err)
  833. if errors.Is(err, gorm.ErrRecordNotFound) {
  834. return global.DeleteNotFoundOrNoPermissionErr
  835. }
  836. return global.DeleteFailedErr
  837. }
  838. if waybillModel.Status != model.WaybillStatusWaitDelivery {
  839. return errors.New(fmt.Sprintf("运单状态为%s,禁止删除", model.WaybillStatusMap[waybillModel.Status]))
  840. }
  841. db := tx.Delete(&waybillModel)
  842. if err = db.Error; err != nil {
  843. e.Log.Errorf("db error: %s", err)
  844. return global.DeleteFailedErr
  845. }
  846. if db.RowsAffected == 0 {
  847. return global.DeleteNotFoundOrNoPermissionErr
  848. }
  849. return nil
  850. }
  851. func (e *Waybill) Receipt(c *dto.WaybillReceiptReq, p *actions.DataPermission) error {
  852. var err error
  853. tx := e.Orm.Begin()
  854. defer func() {
  855. if err != nil {
  856. tx.Rollback()
  857. } else {
  858. tx.Commit()
  859. }
  860. }()
  861. var waybillModel = model.Waybill{}
  862. // 查询运单是否存在
  863. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  864. Where("waybill_no = ?", c.WaybillNo).
  865. First(&waybillModel).Error
  866. if err != nil {
  867. e.Log.Errorf("db error: %s", err)
  868. if errors.Is(err, gorm.ErrRecordNotFound) {
  869. return errors.New(fmt.Sprintf("运单号%s不存在", c.WaybillNo))
  870. }
  871. return errors.New(fmt.Sprintf("运单号%s查询失败", c.WaybillNo))
  872. }
  873. // 查询保温箱信息
  874. var coolerBox = model.CoolerBox{}
  875. err = tx.Scopes(actions.Permission(coolerBox.TableName(), p)).
  876. First(&coolerBox, waybillModel.CoolerBoxId).Error
  877. if err != nil {
  878. e.Log.Errorf("db error: %s", err)
  879. return errors.New("获取保温箱信息失败")
  880. }
  881. if waybillModel.Status == model.WaybillStatusWaitDelivery {
  882. err = errors.New(fmt.Sprintf("运单状态为%s,禁止操作", model.WaybillStatusMap[waybillModel.Status]))
  883. return err
  884. }
  885. if waybillModel.Status == model.WaybillStatusReceipts || waybillModel.Status == model.WaybillStatusRejections {
  886. return nil
  887. }
  888. waybillModel.Status = c.Status
  889. waybillModel.RejectionReason = c.RejectionReason
  890. waybillModel.ReceiptTime = model2.Time(time.Now())
  891. waybillModel.ReceiptImg = c.ReceiptImg
  892. waybillModel.Receiptsign = c.Receiptsign
  893. waybillModel.PaymentStatus = c.PaymentStatus
  894. waybillModel.PaymentType = c.PaymentType
  895. waybillModel.PaymentRemark = c.PaymentRemark
  896. waybillModel.AssessContent = c.AssessContent
  897. waybillModel.AssessStar = c.AssessStar
  898. waybillModel.DeliveryDuration = int(time.Now().Sub(waybillModel.DeliveryTime.Local()).Minutes())
  899. err = tx.Save(&waybillModel).Error
  900. if err != nil {
  901. e.Log.Errorf("db error: %s", err)
  902. return errors.New(fmt.Sprintf("保存运单信息失败:%s", err))
  903. }
  904. var lng, lat string
  905. lng, lat, err = e.GetSite(waybillModel.DeptId, coolerBox.Sn, waybillModel.ReceiptTime.String())
  906. if err != nil {
  907. e.Log.Errorf("获取定位信息失败: %s", err)
  908. return err
  909. }
  910. // 查询任务
  911. var task model.WaybillTask
  912. err = tx.Model(&task).Where("waybill_no = ? and cooler_box_id = ?", c.WaybillNo, coolerBox.Id).
  913. Last(&task).Error
  914. if err != nil {
  915. e.Log.Errorf("db error: %s", err)
  916. return errors.New(fmt.Sprintf("查询运单任务信息失败:%s", err))
  917. }
  918. // 未下车 直接点签收
  919. if time.Time(task.EndTime).IsZero() {
  920. task.EndTime = model2.Time(time.Now())
  921. //task.UpdateBy = p.UserIds
  922. err = tx.Save(&task).Error
  923. if err != nil {
  924. e.Log.Errorf("db error: %s", err)
  925. return errors.New(fmt.Sprintf("保存运单任务信息失败:%s", err))
  926. }
  927. }
  928. var userId int
  929. if p != nil {
  930. userId = p.UserId
  931. }
  932. // 添加签收记录
  933. Logistics := model.WaybillLogistics{
  934. WaybillNo: c.WaybillNo,
  935. Status: c.Status,
  936. CoolerBoxId: coolerBox.Id,
  937. UserId: userId,
  938. Lng: lng,
  939. Lat: lat,
  940. ControlBy: model2.ControlBy{
  941. CreateBy: userId,
  942. },
  943. DeptBy: model2.DeptBy{
  944. DeptId: waybillModel.DeptId,
  945. },
  946. ModelTime: model2.ModelTime{
  947. CreatedAt: waybillModel.ReceiptTime,
  948. },
  949. }
  950. err = tx.Create(&Logistics).Error
  951. if err != nil {
  952. e.Log.Errorf("db error: %s", err)
  953. return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  954. }
  955. return nil
  956. }
  957. // 获取入库 出库 上车 下车 定位信息
  958. func (e *Waybill) GetSite(companyId int, sn string, time string) (lng, lat string, err error) {
  959. // 获取公司秘钥
  960. var company model.SysDept
  961. company, err = model.GetCompanyById(companyId)
  962. if err != nil {
  963. e.Log.Errorf("db error: %s", err)
  964. return lng, lat, model.GetCompanyKeyErr
  965. }
  966. // 获取传感器信息
  967. var deviceSensorList = []nats_server.DeviceSensor_R{}
  968. var count int64
  969. deviceSensorList, count, err = nats_server.Cold_CompanyDeviceSensor_List_ByKey(sn, company.ColdKey)
  970. if err != nil || count == 0 {
  971. err = errors.New("查询设备定位信息失败")
  972. return lng, lat, err
  973. }
  974. var deviceData nats_server.DeviceData_
  975. deviceData, err = nats_server.Cold_ReadDeviceDataBy_T_snid_T_time(deviceSensorList[0].T_sn, deviceSensorList[0].T_id, time)
  976. if err != nil {
  977. err = errors.New("查询设备定位信息失败")
  978. return lng, lat, err
  979. }
  980. if len(deviceData.T_site) > 0 {
  981. site := strings.Split(deviceSensorList[0].T_DeviceSensorData.T_site, ",")
  982. if len(site) == 2 {
  983. lng = site[0]
  984. lat = site[1]
  985. }
  986. }
  987. return lng, lat, nil
  988. }
  989. // 获取今日运单数 未派单 未装车 未入库 运送中
  990. // 本月运单总数 上月运单总数 本年运单总数 上年运单总数
  991. func (e *Waybill) GetBasicsStats(c *dto.WaybillStatsReq, p *actions.DataPermission) dto.WaybillStatsRes {
  992. var res dto.WaybillStatsRes
  993. var data model.Waybill
  994. type DateCount struct {
  995. Date string
  996. Count int64
  997. }
  998. yearCount := make([]DateCount, 0)
  999. monthCount := make([]DateCount, 0)
  1000. now := time.Now()
  1001. todayStartTime := now.Format("2006-01-02") + " 00:00:00"
  1002. todayEndTime := now.Format("2006-01-02") + " 23:59:59"
  1003. // 获取上个月第一天
  1004. firstDayOfLastMonth := time.Date(now.Year(), now.Month()-1, 1, 0, 0, 0, 0, now.Location())
  1005. // 获取去年的第一天
  1006. firstDayOfLastYear := time.Date(now.Year()-1, time.January, 1, 0, 0, 0, 0, now.Location())
  1007. monthStartTime := firstDayOfLastMonth.Format("2006-01-02") + " 00:00:00"
  1008. yearStartTime := firstDayOfLastYear.Format("2006-01-02") + " 00:00:00"
  1009. // 今日总运单数
  1010. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("order_time between ? and ?", todayStartTime, todayEndTime).Count(&res.TodayNum)
  1011. // 待确定
  1012. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusWaitDelivery).Count(&res.WaitDeliveryNum)
  1013. // 配送中
  1014. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusInDeliverys).Count(&res.InDeliveryNum)
  1015. // 已签收
  1016. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusReceipts).Count(&res.ReceiptNum)
  1017. // 已取消
  1018. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p)).Where("status = ?", model.WaybillStatusRejections).Count(&res.RejectionNum)
  1019. // 获取本月,上月数据
  1020. e.Orm.Model(&data).Select("date_format(order_time,'%Y%m') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p)).
  1021. Where("order_time between ? and ?", monthStartTime, now).Group("date").Find(&monthCount)
  1022. for _, month := range monthCount {
  1023. if month.Date == now.Format("200601") {
  1024. res.ThisMonthNum = month.Count
  1025. }
  1026. if month.Date == firstDayOfLastMonth.Format("200601") {
  1027. res.LastMonthNum = month.Count
  1028. }
  1029. }
  1030. // 获取本年,上年数据
  1031. e.Orm.Model(&data).Select("date_format(order_time,'%Y') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p)).
  1032. Where("order_time between ? and ?", yearStartTime, now).Group("date").Find(&yearCount)
  1033. for _, month := range yearCount {
  1034. if month.Date == now.Format("2006") {
  1035. res.ThisYearNum = month.Count
  1036. }
  1037. if month.Date == firstDayOfLastYear.Format("2006") {
  1038. res.LastYearNum = month.Count
  1039. }
  1040. }
  1041. if c.Type == "year" {
  1042. // 获取上个月第一天
  1043. year, _ := strconv.Atoi(c.Date)
  1044. firstDayOfyear := time.Date(year, 1, 1, 0, 0, 0, 0, now.Location())
  1045. lastDayOfyear := time.Date(year, 12, 31, 23, 59, 59, 0, now.Location())
  1046. // 年度数据统计
  1047. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p)).
  1048. Where("order_time between ? and ?", firstDayOfyear, lastDayOfyear).Group("date").Find(&res.Stats)
  1049. }
  1050. if c.Type == "month" {
  1051. // 获取上个月第一天
  1052. month, _ := time.ParseInLocation("2006-01", c.Date, time.Local)
  1053. firstDayOfMonth := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, now.Location())
  1054. lastDayOfMonth := time.Date(month.Year(), month.Month()+1, 1, 23, 59, 59, 0, now.Location()).Add(-time.Hour * 24)
  1055. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m-%d') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p)).
  1056. Where("order_time between ? and ?", firstDayOfMonth, lastDayOfMonth).Group("date").Find(&res.Stats)
  1057. }
  1058. return res
  1059. }
  1060. func GetDeliveryStatsScopes(userId int) func(db *gorm.DB) *gorm.DB {
  1061. return func(db *gorm.DB) *gorm.DB {
  1062. if userId == 0 {
  1063. return db
  1064. }
  1065. return db.Where("delivery_id = ?", userId)
  1066. }
  1067. }
  1068. func GetReCheckStatsScopes(userId int) func(db *gorm.DB) *gorm.DB {
  1069. return func(db *gorm.DB) *gorm.DB {
  1070. if userId == 0 {
  1071. return db
  1072. }
  1073. return db.Where("re_check_id = ?", userId)
  1074. }
  1075. }
  1076. // 获取配送员统计信息
  1077. func (e *Waybill) GetDeliveryStats(c *dto.WaybillUserStatsReq, p *actions.DataPermission) (res []dto.WaybillUserStats) {
  1078. // 获取用户列表
  1079. var userList []model.SysUser
  1080. if err := e.Orm.Model(&userList).Scopes(actions.Permission(model.SysUser{}.TableName(), p), WaybillUserStatsUserIdScopes(c.UserIds)).
  1081. Where("status = 2").Order("created_at desc").Find(&userList).Error; err != nil {
  1082. return nil
  1083. }
  1084. for _, user := range userList {
  1085. stats := e.GetUserStats(c, p, GetDeliveryStatsScopes(user.Id))
  1086. stats.Name = user.NickName
  1087. res = append(res, stats)
  1088. }
  1089. return
  1090. }
  1091. func (e *Waybill) GetReCheckStats(c *dto.WaybillUserStatsReq, p *actions.DataPermission) (res []dto.WaybillUserStats) {
  1092. // 获取用户列表
  1093. var userList []model.SysUser
  1094. if err := e.Orm.Model(&userList).Scopes(actions.Permission(model.SysUser{}.TableName(), p), WaybillUserStatsUserIdScopes(c.UserIds)).
  1095. Where("status = 2").Order("created_at desc").Find(&userList).Error; err != nil {
  1096. return nil
  1097. }
  1098. for _, user := range userList {
  1099. stats := e.GetUserStats(c, p, GetReCheckStatsScopes(user.Id))
  1100. stats.Name = user.NickName
  1101. res = append(res, stats)
  1102. }
  1103. return
  1104. }
  1105. func WaybillUserStatsUserIdScopes(userIds []int) func(db *gorm.DB) *gorm.DB {
  1106. return func(db *gorm.DB) *gorm.DB {
  1107. if len(userIds) == 0 {
  1108. return db
  1109. }
  1110. if len(userIds) == 1 {
  1111. return db.Where("id = ?", userIds[0])
  1112. }
  1113. return db.Where("id in (?)", userIds)
  1114. }
  1115. }
  1116. func GetUserBasicsStatsScopes(userId int) func(db *gorm.DB) *gorm.DB {
  1117. return func(db *gorm.DB) *gorm.DB {
  1118. if userId == 0 {
  1119. return db
  1120. }
  1121. return db.Where("delivery_id = ? or re_check_id = ? or create_by = ?", userId, userId, userId)
  1122. }
  1123. }
  1124. func (e *Waybill) GetUserBasicsStats(c *dto.WaybillStatsReq, p *actions.DataPermission, scopes func(*gorm.DB) *gorm.DB) dto.WaybillStatsRes {
  1125. var res dto.WaybillStatsRes
  1126. var data model.Waybill
  1127. type DateCount struct {
  1128. Date string
  1129. Count int64
  1130. }
  1131. yearCount := make([]DateCount, 0)
  1132. monthCount := make([]DateCount, 0)
  1133. now := time.Now()
  1134. todayStartTime := now.Format("2006-01-02") + " 00:00:00"
  1135. todayEndTime := now.Format("2006-01-02") + " 23:59:59"
  1136. // 获取上个月第一天
  1137. firstDayOfLastMonth := time.Date(now.Year(), now.Month()-1, 1, 0, 0, 0, 0, now.Location())
  1138. // 获取去年的第一天
  1139. firstDayOfLastYear := time.Date(now.Year()-1, time.January, 1, 0, 0, 0, 0, now.Location())
  1140. monthStartTime := firstDayOfLastMonth.Format("2006-01-02") + " 00:00:00"
  1141. yearStartTime := firstDayOfLastYear.Format("2006-01-02") + " 00:00:00"
  1142. // 今日总运单数
  1143. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  1144. Where("order_time between ? and ?", todayStartTime, todayEndTime).Count(&res.TodayNum)
  1145. // 待派单
  1146. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  1147. Where("status = ?", model.WaybillStatusWaitDelivery).Count(&res.WaitDeliveryNum)
  1148. // 配送中
  1149. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  1150. Where("status = ?", model.WaybillStatusInDeliverys).Count(&res.InDeliveryNum)
  1151. // 已送达
  1152. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  1153. Where("status = ?", model.WaybillStatusReceipts).Count(&res.ReceiptNum)
  1154. // 已取消
  1155. e.Orm.Model(&data).Scopes(actions.Permission(data.TableName(), p), scopes).
  1156. Where("status = ?", model.WaybillStatusRejections).Count(&res.RejectionNum)
  1157. // 获取本月,上月数据
  1158. e.Orm.Model(&data).Select("date_format(order_time,'%Y%m') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p), scopes).
  1159. Where("order_time between ? and ?", monthStartTime, now).Group("date").Find(&monthCount)
  1160. for _, month := range monthCount {
  1161. if month.Date == now.Format("200601") {
  1162. res.ThisMonthNum = month.Count
  1163. }
  1164. if month.Date == firstDayOfLastMonth.Format("200601") {
  1165. res.LastMonthNum = month.Count
  1166. }
  1167. }
  1168. // 获取本年,上年数据
  1169. e.Orm.Model(&data).Select("date_format(order_time,'%Y') date,count(1) as count ").Scopes(actions.Permission(data.TableName(), p), scopes).
  1170. Where("order_time between ? and ?", yearStartTime, now).Group("date").Find(&yearCount)
  1171. for _, month := range yearCount {
  1172. if month.Date == now.Format("2006") {
  1173. res.ThisYearNum = month.Count
  1174. }
  1175. if month.Date == firstDayOfLastYear.Format("2006") {
  1176. res.LastYearNum = month.Count
  1177. }
  1178. }
  1179. if c.Type == "year" {
  1180. // 获取上个月第一天
  1181. year, _ := strconv.Atoi(c.Date)
  1182. firstDayOfyear := time.Date(year, 1, 1, 0, 0, 0, 0, now.Location())
  1183. lastDayOfyear := time.Date(year, 12, 31, 23, 59, 59, 0, now.Location())
  1184. // 年度数据统计
  1185. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p), scopes).
  1186. Where("order_time between ? and ?", firstDayOfyear, lastDayOfyear).Group("date").Find(&res.Stats)
  1187. }
  1188. if c.Type == "month" {
  1189. // 获取上个月第一天
  1190. month, _ := time.ParseInLocation("2006-01", c.Date, time.Local)
  1191. firstDayOfMonth := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, now.Location())
  1192. lastDayOfMonth := time.Date(month.Year(), month.Month()+1, 1, 23, 59, 59, 0, now.Location()).Add(-time.Hour * 24)
  1193. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m-%d') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p), scopes).
  1194. Where("order_time between ? and ?", firstDayOfMonth, lastDayOfMonth).Group("date").Find(&res.Stats)
  1195. }
  1196. return res
  1197. }
  1198. func (e *Waybill) GetUserStats(c *dto.WaybillUserStatsReq, p *actions.DataPermission, scopes func(*gorm.DB) *gorm.DB) dto.WaybillUserStats {
  1199. var res dto.WaybillUserStats
  1200. var data model.Waybill
  1201. type DateCount struct {
  1202. Date string
  1203. Count int64
  1204. }
  1205. now := time.Now()
  1206. if c.Type == "year" {
  1207. // 获取上个月第一天
  1208. year, _ := strconv.Atoi(c.Date)
  1209. firstDayOfyear := time.Date(year, 1, 1, 0, 0, 0, 0, now.Location())
  1210. lastDayOfyear := time.Date(year, 12, 31, 23, 59, 59, 0, now.Location())
  1211. // 年度数据统计
  1212. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p), scopes).
  1213. Where("order_time between ? and ?", firstDayOfyear, lastDayOfyear).Group("date").Find(&res.Stats)
  1214. // 获取这个月的所有日期
  1215. allDates := getAllDatesInYear(c.Date)
  1216. // 补齐缺失日期的数据
  1217. res.Stats = completeMissingDates(allDates, res.Stats)
  1218. }
  1219. if c.Type == "month" {
  1220. // 获取上个月第一天
  1221. month, _ := time.ParseInLocation("2006-01", c.Date, time.Local)
  1222. firstDayOfMonth := time.Date(month.Year(), month.Month(), 1, 0, 0, 0, 0, now.Location())
  1223. lastDayOfMonth := time.Date(month.Year(), month.Month()+1, 1, 23, 59, 59, 0, now.Location()).Add(-time.Hour * 24)
  1224. e.Orm.Model(&data).Select("date_format(order_time,'%Y-%m-%d') date,count(1) as num ").Scopes(actions.Permission(data.TableName(), p), scopes).
  1225. Where("order_time between ? and ?", firstDayOfMonth, lastDayOfMonth).Group("date").Find(&res.Stats)
  1226. // 获取这个月的所有日期
  1227. allDates := getAllDatesInMonth(c.Date)
  1228. // 补齐缺失日期的数据
  1229. res.Stats = completeMissingDates(allDates, res.Stats)
  1230. }
  1231. return res
  1232. }
  1233. // 获取指定月份的所有日期
  1234. func getAllDatesInMonth(month string) []string {
  1235. var dates []string
  1236. layout := "2006-01-02"
  1237. firstDay, _ := time.Parse(layout, month+"-01")
  1238. if time.Now().Before(firstDay) {
  1239. return dates
  1240. }
  1241. lastDay := firstDay.AddDate(0, 1, -1)
  1242. if time.Now().Before(lastDay) {
  1243. lastDay = time.Now()
  1244. }
  1245. for d := firstDay; !d.After(lastDay); d = d.AddDate(0, 0, 1) {
  1246. dates = append(dates, d.Format(layout))
  1247. }
  1248. return dates
  1249. }
  1250. // 获取指定年份的所有日期
  1251. func getAllDatesInYear(year string) []string {
  1252. var dates []string
  1253. layout := "2006-01"
  1254. firstDay, _ := time.Parse(layout, year+"-01")
  1255. lastDay := firstDay.AddDate(1, 0, -1)
  1256. if time.Now().Before(firstDay) {
  1257. return dates
  1258. }
  1259. if time.Now().Before(lastDay) {
  1260. lastDay = time.Now()
  1261. }
  1262. for d := firstDay; !d.After(lastDay); d = d.AddDate(0, 1, 0) {
  1263. dates = append(dates, d.Format(layout))
  1264. }
  1265. return dates
  1266. }
  1267. // 补齐缺失日期的数据
  1268. func completeMissingDates(allDates []string, stats []dto.WaybillStats) []dto.WaybillStats {
  1269. dateMap := make(map[string]int64)
  1270. for _, stat := range stats {
  1271. dateMap[stat.Date] = stat.Num
  1272. }
  1273. var completedStats []dto.WaybillStats
  1274. for _, date := range allDates {
  1275. num, exists := dateMap[date]
  1276. if !exists {
  1277. num = 0
  1278. }
  1279. completedStats = append(completedStats, dto.WaybillStats{Date: date, Num: num})
  1280. }
  1281. return completedStats
  1282. }
  1283. // 获取运单所有温湿度素具
  1284. func (e *Waybill) GetAllData(c *dto.WaybillGetByWaybillNoReq) ([]nats_server.DeviceData_R, []WaybillPDF, error) {
  1285. var err error
  1286. var data model.WaybillTask
  1287. var waybill model.Waybill
  1288. var taskList []model.WaybillTask
  1289. var waybillPDF []WaybillPDF
  1290. dataList := make([]nats_server.DeviceData_R, 0)
  1291. err = e.Orm.Model(&waybill).Where("waybill_no = ?", c.WaybillNo).First(&waybill).Error
  1292. if err != nil {
  1293. e.Log.Errorf("db error: %s", err)
  1294. return dataList, waybillPDF, errors.New("获取运单信息失败")
  1295. }
  1296. // 未签收,不返回数据
  1297. if waybill.Status != model.WaybillStatusReceipts {
  1298. return dataList, waybillPDF, nil
  1299. }
  1300. // 获取公司秘钥
  1301. var company model.SysDept
  1302. company, err = model.GetCompanyById(waybill.DeptId)
  1303. if err != nil {
  1304. e.Log.Errorf("db error: %s", err)
  1305. return dataList, waybillPDF, model.GetCompanyKeyErr
  1306. }
  1307. err = e.Orm.Model(&data).
  1308. Where("waybill_no = ?", c.WaybillNo).
  1309. Order("id desc").
  1310. Find(&taskList).Error
  1311. if err != nil {
  1312. e.Log.Errorf("db error: %s", err)
  1313. return dataList, waybillPDF, global.GetFailedErr
  1314. }
  1315. // 获取最后一个任务id
  1316. var lastWaybillTask model.WaybillTask
  1317. err = e.Orm.Model(&lastWaybillTask).Where("waybill_no = ?", c.WaybillNo).Last(&lastWaybillTask).Error
  1318. if err != nil {
  1319. e.Log.Errorf("db error: %s", err)
  1320. err = errors.New("获取运单信息错误!")
  1321. return dataList, waybillPDF, err
  1322. }
  1323. // 创建名称到权重的映射
  1324. orderMap := make(map[string]int)
  1325. for i, v := range taskList {
  1326. orderMap[v.Sn] = i
  1327. }
  1328. for i := 0; i < len(taskList); i++ {
  1329. // 获取传感器信息
  1330. deviceSensorList, _, _ := nats_server.Cold_CompanyDeviceSensor_List_ByKey(taskList[i].Sn, company.ColdKey)
  1331. var T_snid string
  1332. var list []nats_server.DeviceData_R
  1333. for _, r := range deviceSensorList {
  1334. T_snid += fmt.Sprintf("%s,%d|", r.T_sn, r.T_id)
  1335. }
  1336. var count int64
  1337. list, count, err = nats_server.Cold_ReadDeviceDataListBy_T_snid(T_snid, taskList[i].StartTime.String(), taskList[i].EndTime.String(), 0, 9999)
  1338. if err != nil {
  1339. e.Log.Errorf("nats 获取温湿度信息失败: %s", err)
  1340. return dataList, waybillPDF, global.GetFailedErr
  1341. }
  1342. firstMap := map[int]nats_server.DeviceData_R{}
  1343. lastMap := map[int]nats_server.DeviceData_R{}
  1344. if count > 0 {
  1345. for _, v := range deviceSensorList {
  1346. for j := 0; j < len(list); j++ {
  1347. if v.T_id == list[j].T_id {
  1348. if list[j].T_time != taskList[i].StartTime.String() {
  1349. firstData := list[j]
  1350. firstData.T_time = taskList[i].StartTime.String()
  1351. firstMap[v.T_id] = firstData
  1352. count += 1
  1353. }
  1354. break
  1355. }
  1356. }
  1357. if waybill.Status == model.WaybillStatusReceipts {
  1358. for k := len(list) - 1; k >= 0; k-- {
  1359. if v.T_id == list[k].T_id {
  1360. if taskList[i].Id == lastWaybillTask.Id && list[k].T_time != taskList[i].EndTime.String() && !time.Time(taskList[i].EndTime).IsZero() {
  1361. lastData := list[k]
  1362. lastData.T_time = taskList[i].EndTime.String()
  1363. lastMap[v.T_id] = lastData
  1364. count += 1
  1365. }
  1366. break
  1367. }
  1368. }
  1369. }
  1370. }
  1371. }
  1372. for _, v := range firstMap {
  1373. list = append(list, v)
  1374. }
  1375. for _, v := range lastMap {
  1376. list = append(list, v)
  1377. }
  1378. sort.Slice(list, func(x, y int) bool {
  1379. if list[x].T_time == list[y].T_time {
  1380. // 如果时间相同,则按预设顺序排序
  1381. return orderMap[list[x].T_sn] < orderMap[list[y].T_sn]
  1382. }
  1383. return list[x].T_time > list[y].T_time
  1384. })
  1385. dataList = append(dataList, list...)
  1386. waybillPDF = append(waybillPDF, WaybillPDF{
  1387. Data: list,
  1388. DeviceSensorList: deviceSensorList,
  1389. Task: taskList[i],
  1390. })
  1391. }
  1392. sort.Slice(dataList, func(i, j int) bool {
  1393. if dataList[i].T_time == dataList[j].T_time {
  1394. // 如果时间相同,则按预设顺序排序
  1395. return orderMap[dataList[i].T_sn] < orderMap[dataList[j].T_sn]
  1396. }
  1397. return dataList[i].T_time < dataList[j].T_time
  1398. })
  1399. return dataList, waybillPDF, nil
  1400. }
  1401. type WaybillPDF struct {
  1402. Data []nats_server.DeviceData_R `json:"data"`
  1403. DeviceSensorList []nats_server.DeviceSensor_R `json:"deviceSensorList"`
  1404. Task model.WaybillTask `json:"task"`
  1405. }
  1406. // Insert 创建Waybill对象
  1407. func (e *Waybill) InsertByOrderId(c *dto.WeianGetWaybillNoReq) error {
  1408. var err error
  1409. var data model.Waybill
  1410. tx := e.Orm.Begin()
  1411. defer func() {
  1412. if err != nil {
  1413. tx.Rollback()
  1414. } else {
  1415. tx.Commit()
  1416. }
  1417. }()
  1418. var company model.SysDept
  1419. var i int64
  1420. err = e.Orm.Model(&company).Where("name = ?", c.CompanyName).Count(&i).Error
  1421. if err != nil {
  1422. e.Log.Errorf("db error: %s", err)
  1423. return global.CreateFailedErr
  1424. }
  1425. if i == 0 {
  1426. err = errors.New("公司名称不存在!")
  1427. e.Log.Errorf("db error: %s", err)
  1428. return err
  1429. }
  1430. var no string
  1431. for {
  1432. no = time.Now().Format("200601021504") + utils.GetRandString(6, "0123456789", 0)
  1433. var j int64
  1434. err = e.Orm.Model(&data).Where("waybill_no = ?", no).Count(&j).Error
  1435. if err != nil {
  1436. continue
  1437. }
  1438. if j == 0 {
  1439. break
  1440. }
  1441. }
  1442. // 添加运单
  1443. data.WaybillNo = no
  1444. data.OrderNo = c.OrderId
  1445. data.DeptId = company.Id
  1446. data.Status = 1
  1447. data.OrderTime = model2.Time(time.Now())
  1448. err = tx.Create(&data).Error
  1449. if err != nil {
  1450. e.Log.Errorf("db error: %s", err)
  1451. return global.CreateFailedErr
  1452. }
  1453. c.WaybillNo = data.WaybillNo
  1454. return nil
  1455. }
  1456. // CreateSole 生成唯一订单编号
  1457. func (e *Waybill) CreateSole() (string, error) {
  1458. var waybill model.Waybill
  1459. var err error
  1460. var count int64
  1461. format := time.Now().Format("20060102")
  1462. un := time.Now().Unix()
  1463. waybillno := fmt.Sprintf("%v%v", format, un)
  1464. err = e.Orm.Model(&waybill).Where("waybill_no = ?", waybillno).Count(&count).Error
  1465. if count > 0 {
  1466. return e.CreateSole()
  1467. }
  1468. if err != nil {
  1469. e.Log.Errorf("生成订单号错误: %s", err)
  1470. err = errors.New("生成订单号错误,请重新生成")
  1471. return "", err
  1472. }
  1473. return waybillno, nil
  1474. }
  1475. // WaybillTurnarounds 订单转门店
  1476. func (e *Waybill) WaybillTurnarounds(c *dto.WaybillTurnarounds, p *actions.DataPermission) error {
  1477. var err error
  1478. var waybillModel model.Waybill
  1479. var count int64
  1480. //查询订单是否存在
  1481. tx := e.Orm.Begin()
  1482. defer func() {
  1483. if err != nil {
  1484. tx.Rollback()
  1485. } else {
  1486. tx.Commit()
  1487. }
  1488. }()
  1489. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  1490. Where("waybill_no = ?", c.WaybillNo).
  1491. First(&waybillModel).Count(&count).Error
  1492. if err != nil {
  1493. e.Log.Errorf("db error: %s", err)
  1494. if errors.Is(err, gorm.ErrRecordNotFound) {
  1495. return global.GetNotFoundOrNoPermissionErr
  1496. }
  1497. return global.GetFailedErr
  1498. }
  1499. if count == 0 {
  1500. return errors.New("订单不存在")
  1501. }
  1502. //查询门店是否存在可以转换
  1503. var data model.SysDept
  1504. var Depts []model.SysDept
  1505. err = e.Orm.Model(&data).
  1506. Scopes(
  1507. CompanyIdScopesUser(p.DeptId),
  1508. ).Find(&Depts).Error
  1509. if err != nil {
  1510. e.Log.Errorf("db error: %s", err)
  1511. return global.GetFailedErr
  1512. }
  1513. contains := false
  1514. for _, v := range Depts {
  1515. if v.Id == c.DeptId {
  1516. contains = true
  1517. break
  1518. } else {
  1519. contains = false
  1520. }
  1521. }
  1522. if !contains {
  1523. return errors.New("转门店不存在")
  1524. }
  1525. waybillModel.DeptId = c.DeptId
  1526. update := tx.Updates(&waybillModel)
  1527. if update.Error != nil {
  1528. e.Log.Errorf("db error: %s", update.Error)
  1529. return global.UpdateFailedErr
  1530. }
  1531. return nil
  1532. }