waybill.go 54 KB

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