waybill.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  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.waybill_no = ?", d.WaybillNo).
  266. Joins("left join drug on drug.waybill_no = waybill.waybill_no").
  267. Preload("Dept").
  268. Preload("CoolerBox").
  269. Preload("Delivery").
  270. Preload("ReCheck").
  271. First(waybillModel).Error
  272. if err != nil {
  273. e.Log.Errorf("db error: %s", err)
  274. if errors.Is(err, gorm.ErrRecordNotFound) {
  275. return global.GetNotFoundOrNoPermissionErr
  276. }
  277. return global.GetFailedErr
  278. }
  279. var drugs []model.Drug
  280. e.Orm.Where("drug.waybill_no = ?", waybillModel.WaybillNo).Find(&drugs)
  281. waybillModel.Drugs = drugs
  282. return nil
  283. }
  284. // Insert 创建Waybill对象
  285. func (e *Waybill) Insert(c *dto.WaybillInsertReq) error {
  286. var err error
  287. var data model.Waybill
  288. tx := e.Orm.Begin()
  289. defer func() {
  290. if err != nil {
  291. tx.Rollback()
  292. } else {
  293. tx.Commit()
  294. }
  295. }()
  296. var no string
  297. for {
  298. no = time.Now().Format("200601021504") + utils.GetRandString(6, "0123456789", 0)
  299. var j int64
  300. err = e.Orm.Model(&data).Where("waybill_no = ?", no).Count(&j).Error
  301. if err != nil {
  302. continue
  303. }
  304. if j == 0 {
  305. break
  306. }
  307. }
  308. // 添加运单
  309. data.WaybillNo = no
  310. sole, err := e.CreateSole()
  311. if err != nil {
  312. err = errors.New("生成运单号失败")
  313. return err
  314. }
  315. data.OrderNo = sole
  316. c.Generate(&data)
  317. if c.IsPhone {
  318. data.Status = model.WaybillStatusInDeliverys
  319. data.AssignmentStatus = 2
  320. }
  321. err = tx.Create(&data).Error
  322. if err != nil {
  323. e.Log.Errorf("db error: %s", err)
  324. return global.CreateFailedErr
  325. }
  326. c.Id = data.Id
  327. // 保存发货地址
  328. if c.SaveConsigneeAddress {
  329. // 查询地址是否存在
  330. address := model.Address{}
  331. err = e.Orm.Where("address = ? and phone = ? and name = ? and dept_id = ? and address_type = 'consignee'",
  332. c.ConsigneeAddressDetails, c.ConsigneeAddressPhone, c.ConsigneeAddressName, c.DeptId).First(&address).Error
  333. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  334. address.Address = c.ConsigneeAddressDetails
  335. address.Phone = c.ConsigneeAddressPhone
  336. address.Name = c.ConsigneeAddressName
  337. address.DeptId = c.DeptId
  338. address.AddressType = "consignee"
  339. err = tx.Create(&address).Error
  340. if err != nil {
  341. e.Log.Errorf("创建地址失败: %s", err)
  342. return global.CreateFailedErr
  343. }
  344. }
  345. }
  346. if len(c.Drugs) > 0 {
  347. for _, drug := range c.Drugs {
  348. var drugs model.Drug
  349. drugs.WaybillNo = no
  350. drugs.Drug_ent_base_info_id = drug.Drug_ent_base_info_id
  351. drugs.Ent_name = drug.Ent_name
  352. drugs.Physic_name = drug.Physic_name
  353. drugs.Approval_licence_no = drug.Approval_licence_no
  354. drugs.Prepn_spec = drug.Prepn_spec
  355. drugs.Physic_type_desc = drug.Physic_type_desc
  356. drugs.Pkg_spec_crit = drug.Pkg_spec_crit
  357. drugs.Prepn_type_desc = drug.Prepn_type_desc
  358. drugs.Code = drug.Code
  359. err = tx.Save(&drugs).Error
  360. if err != nil {
  361. e.Log.Errorf("db error: %s", err)
  362. return errors.New("保存药品信息失败")
  363. }
  364. }
  365. }
  366. return nil
  367. }
  368. // Update 修改Waybill对象
  369. func (e *Waybill) Update(c *dto.WaybillUpdateReq, p *actions.DataPermission) error {
  370. var err error
  371. tx := e.Orm.Begin()
  372. defer func() {
  373. if err != nil {
  374. tx.Rollback()
  375. } else {
  376. tx.Commit()
  377. }
  378. }()
  379. var waybillModel = model.Waybill{}
  380. // 查询运单是否存在
  381. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  382. First(&waybillModel, c.GetId()).Error
  383. if err != nil {
  384. e.Log.Errorf("db error: %s", err)
  385. if errors.Is(err, gorm.ErrRecordNotFound) {
  386. return global.UpdateNotFoundOrNoPermissionErr
  387. }
  388. return global.UpdateFailedErr
  389. }
  390. c.Generate(&waybillModel)
  391. err = tx.Save(&waybillModel).Error
  392. if err != nil {
  393. e.Log.Errorf("db error: %s", err)
  394. return global.UpdateFailedErr
  395. }
  396. c.Id = waybillModel.Id
  397. return nil
  398. }
  399. // 审核订单
  400. func (e *Waybill) Audit(c *dto.WaybillUpdateReqaudit, p *actions.DataPermission) error {
  401. var err error
  402. tx := e.Orm.Begin()
  403. defer func() {
  404. if err != nil {
  405. tx.Rollback()
  406. } else {
  407. tx.Commit()
  408. }
  409. }()
  410. var waybillModel = model.Waybill{}
  411. // 查询运单是否存在
  412. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  413. First(&waybillModel, c.GetId()).Error
  414. if err != nil {
  415. e.Log.Errorf("db error: %s", err)
  416. if errors.Is(err, gorm.ErrRecordNotFound) {
  417. return global.UpdateNotFoundOrNoPermissionErr
  418. }
  419. return global.UpdateFailedErr
  420. }
  421. c.Generate(&waybillModel)
  422. waybillModel.Status = c.Status
  423. waybillModel.ReCheckId = p.UserId
  424. err = tx.Updates(&waybillModel).Error
  425. if err != nil {
  426. e.Log.Errorf("db error: %s", err)
  427. return global.UpdateFailedErr
  428. }
  429. c.Id = waybillModel.Id
  430. return nil
  431. }
  432. // 管理员审核订单
  433. func (e *Waybill) AdminAudit(c *dto.WaybillAdmin, p *actions.DataPermission) error {
  434. var err error
  435. tx := e.Orm.Begin()
  436. defer func() {
  437. if err != nil {
  438. tx.Rollback()
  439. } else {
  440. tx.Commit()
  441. }
  442. }()
  443. var waybillModel = model.Waybill{}
  444. // 查询运单是否存在
  445. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  446. First(&waybillModel, c.GetId()).Error
  447. if err != nil {
  448. e.Log.Errorf("db error: %s", err)
  449. if errors.Is(err, gorm.ErrRecordNotFound) {
  450. return global.UpdateNotFoundOrNoPermissionErr
  451. }
  452. return global.UpdateFailedErr
  453. }
  454. c.Generate(&waybillModel)
  455. waybillModel.AdminAuditRemark = c.AdminAuditRemark
  456. err = tx.Updates(&waybillModel).Error
  457. if err != nil {
  458. e.Log.Errorf("db error: %s", err)
  459. return global.UpdateFailedErr
  460. }
  461. c.Id = waybillModel.Id
  462. return nil
  463. }
  464. func (e *Waybill) UpdateStatus(c *dto.UpdateStatusReq, p *actions.DataPermission) error {
  465. var err error
  466. tx := e.Orm.Begin()
  467. defer func() {
  468. if err != nil {
  469. tx.Rollback()
  470. } else {
  471. tx.Commit()
  472. }
  473. }()
  474. // 查询运单是否存在
  475. for _, v := range c.Id {
  476. var waybillModel = model.Waybill{}
  477. err = e.Orm.Scopes(actions.Permission(waybillModel.TableName(), p)).
  478. First(&waybillModel, v).Error
  479. if err != nil {
  480. e.Log.Errorf("db error: %s", err)
  481. if errors.Is(err, gorm.ErrRecordNotFound) {
  482. return global.UpdateNotFoundOrNoPermissionErr
  483. }
  484. return global.UpdateFailedErr
  485. }
  486. waybillModel.Status = c.Status
  487. err = tx.Table(waybillModel.TableName()).Where("id=?", v).Update("status", c.Status).Error
  488. if err != nil {
  489. e.Log.Errorf("db error: %s", err)
  490. return global.UpdateFailedErr
  491. }
  492. // 查询任务
  493. //var logistics model.WaybillLogistics
  494. //err = tx.Model(&logistics).Where("waybill_no = ? and status = ?", waybillModel.WaybillNo, model.WaybillStatusInDeliverys).
  495. // Last(&logistics).Error
  496. //if err != nil {
  497. // if errors.Is(err, gorm.ErrRecordNotFound) {
  498. // // 添加物流
  499. // logisticsObj := model.WaybillLogistics{
  500. // WaybillNo: waybillModel.WaybillNo,
  501. // Status: waybillModel.Status,
  502. // ControlBy: model2.ControlBy{
  503. // CreateBy: p.UserId,
  504. // },
  505. // DeptBy: model2.DeptBy{
  506. // DeptId: p.DeptId,
  507. // },
  508. // }
  509. // err = tx.Create(&logisticsObj).Error
  510. // if err != nil {
  511. // e.Log.Errorf("db error: %s", err)
  512. // return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  513. // }
  514. // } else {
  515. // e.Log.Errorf("db error: %s", err)
  516. // return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  517. // }
  518. //}
  519. //err = tx.Save(&logistics).Error
  520. //if err != nil {
  521. // e.Log.Errorf("db error: %s", err)
  522. // return errors.New(fmt.Sprintf("保存运单物流信息失败:%s", err))
  523. //}
  524. }
  525. //err = tx.Save(&waybillModel).Error
  526. //if err != nil {
  527. // e.Log.Errorf("db error: %s", err)
  528. // return global.UpdateFailedErr
  529. //}
  530. return nil
  531. }
  532. // 派单
  533. func (e *Waybill) Delivery(c *dto.WaybillDeliveryReq, p *actions.DataPermission) error {
  534. var err error
  535. tx := e.Orm.Begin()
  536. defer func() {
  537. if err != nil {
  538. tx.Rollback()
  539. } else {
  540. tx.Commit()
  541. }
  542. }()
  543. if !lib.StrListEqual(c.IceRaftCode, c.OldIceRaftCode) {
  544. // 获取删除的冰排列表
  545. //missingIceRaftCode = lib.FindStrListMissingData(c.OldIceRaftCode, c.IceRaftCode)
  546. //if len(missingIceRaftCode) > 0 {
  547. // // 删除冰排出库记录
  548. // IceRaftList := []model.IceRaft{}
  549. // err = tx.Model(&model.IceRaft{}).Where("code in (?)", missingIceRaftCode).Find(&IceRaftList).Error
  550. // if err != nil {
  551. // e.Log.Errorf("db error: %s", err)
  552. // return errors.New("获取冰排列表失败")
  553. // }
  554. // for _, iceRaft := range IceRaftList {
  555. // // 获取冰排记录
  556. // err = tx.Model(&model.IceRaftRecord{}).
  557. // Where("ice_raft_id = ? and status = ?", iceRaft.Id, model.IceRaftRecordStatusUsing).
  558. // Updates(map[string]interface{}{
  559. // "status": model.IceRaftRecordStatusWaitUse,
  560. // "out_storage_time": nil,
  561. // "cooler_box_id": 0,
  562. // }).Error
  563. // if err != nil {
  564. // e.Log.Errorf("db error: %s", err)
  565. // return errors.New(fmt.Sprintf("冰排【%s】返库失败", iceRaft.Code))
  566. // }
  567. // }
  568. //}
  569. // 获取新增的冰排列表
  570. extraData := lib.FindStrListExtraData(c.OldIceRaftCode, c.IceRaftCode)
  571. if len(extraData) > 0 {
  572. for _, code := range extraData {
  573. var iceRaft model.IceRaft
  574. err = tx.Model(&model.IceRaft{}).Where("code = ?", code).Preload("IceRaftRecord").First(&iceRaft).Error
  575. if err != nil {
  576. e.Log.Errorf("db error: %s", err)
  577. if errors.Is(err, gorm.ErrRecordNotFound) {
  578. return errors.New(fmt.Sprintf("冰排【%s】不存在", code))
  579. } else {
  580. return errors.New(fmt.Sprintf("获取冰排【%s】信息失败", code))
  581. }
  582. }
  583. if iceRaft.IceRaftRecord.Status != model.IceRaftRecordStatusWaitUse {
  584. err = errors.New(fmt.Sprintf("冰排【%s】状态为%s,出库保温箱失败!", code, model.GetIceRaftRecordStatus(iceRaft.IceRaftRecord.Status)))
  585. return err
  586. }
  587. // 获取冰排记录
  588. err = tx.Model(&model.IceRaftRecord{}).
  589. Where("ice_raft_id = ? and status = ?", iceRaft.Id, model.IceRaftRecordStatusWaitUse).
  590. Updates(map[string]interface{}{
  591. "status": model.IceRaftRecordStatusUsing,
  592. "out_storage_time": time.Now(),
  593. "cooler_box_id": c.CoolerBoxId,
  594. }).Error
  595. if err != nil {
  596. e.Log.Errorf("db error: %s", err)
  597. return errors.New(fmt.Sprintf("冰排【%s】出库失败", iceRaft.Code))
  598. }
  599. }
  600. }
  601. }
  602. var coolerBox = model.CoolerBox{}
  603. // 查询保温箱信息
  604. if c.CoolerBoxId != 0 {
  605. err = tx.Scopes(actions.Permission(coolerBox.TableName(), p)).
  606. First(&coolerBox, c.CoolerBoxId).Error
  607. if err != nil {
  608. e.Log.Errorf("获取保温箱信息失败: %s", err)
  609. return errors.New("获取保温箱信息失败")
  610. }
  611. }
  612. var user model.SysUser
  613. first := e.Orm.Table(user.TableName()).Where("id = ?", p.UserId).First(&user)
  614. if first.Error != nil {
  615. return global.GetFailedErr
  616. }
  617. for _, id := range c.WaybillIds {
  618. var waybillModel = model.Waybill{}
  619. // 查询运单是否存在
  620. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  621. First(&waybillModel, id).Error
  622. if err != nil {
  623. e.Log.Errorf("db error: %s", err)
  624. if errors.Is(err, gorm.ErrRecordNotFound) {
  625. return global.UpdateNotFoundOrNoPermissionErr
  626. }
  627. return global.UpdateFailedErr
  628. }
  629. //派单时添加
  630. //waybillModeStatus := waybillModel.Status
  631. if waybillModel.Status == model.WaybillStatusInDeliverys ||
  632. (waybillModel.Status == model.WaybillStatusInDeliverys && waybillModel.CoolerBoxId != c.CoolerBoxId) ||
  633. (waybillModel.Status == model.WaybillStatusInDeliverys && !lib.StrListEqual(c.IceRaftCode, c.OldIceRaftCode)) {
  634. waybillModel.Status = model.WaybillStatusInDeliverys
  635. waybillModel.TamperProofLabel = c.TamperProofLabel
  636. waybillModel.TamperProofLabelImg = c.TamperProofLabelImg // 防拆标签
  637. waybillModel.DeliveryId = c.DeliveryId
  638. waybillModel.AssignmentStatus = 2 // 分配状态 2 已派单
  639. waybillModel.CoolerBoxId = c.CoolerBoxId
  640. waybillModel.DeliveryTime = model2.Time(time.Now())
  641. waybillModel.IceRaftCode = c.IceRaftCode
  642. if c.Status == model.WaybillStatusInShippeds {
  643. waybillModel.Status = c.Status
  644. // 查询保温箱信息
  645. //var coolerBoxModel model.CoolerBox
  646. //err = e.Orm.Scopes(actions.Permission(coolerBoxModel.TableName(), p)).
  647. // First(&coolerBoxModel, c.CoolerBoxId).Error
  648. //if err != nil {
  649. // e.Log.Errorf("查询保温箱信息失败: %s", err)
  650. // return errors.New("查询保温箱信息失败")
  651. //}
  652. var data model.IceRaft
  653. var list []string
  654. err := e.Orm.Model(&data).
  655. Select("ice_raft.code").
  656. Scopes(
  657. actions.Permission(data.TableName(), p),
  658. IceRaftNameRecordStatusScopes(model.IceRaftRecordStatusUsing),
  659. IceRaftNameRecordCoolerBoxIdScopes(coolerBox.Id),
  660. ).
  661. Joins("left join ice_raft_record on ice_raft.ice_raft_record_id = ice_raft_record.id").
  662. Find(&list).Error
  663. if err != nil {
  664. e.Log.Errorf("db error: %s", err)
  665. return errors.New("获取冰排编号失败")
  666. }
  667. //查询保温箱记录信息状态为1使用中
  668. var cooler model.CoolerBoxRecord
  669. var count int64
  670. e.Orm.Scopes(actions.Permission(cooler.TableName(), p)).
  671. First(&cooler).Where("cooler_box_id = ?", coolerBox.Id).Where("status = ?", 1).Count(&count)
  672. if count == 0 {
  673. cooler.CoolerUseUsers = user.NickName
  674. cooler.HistoryCode = append(cooler.HistoryCode, list...)
  675. cooler.HistoryCode = cDto.UniqueSlice(cooler.HistoryCode)
  676. cooler.CoolerUserTime = model2.Time(time.Now())
  677. cooler.Status = "2" //使用结束
  678. err := e.Orm.Save(&cooler).Error
  679. if err != nil {
  680. e.Log.Errorf("保存保温箱记录失败: %s", err)
  681. return errors.New("保存保温箱记录失败")
  682. }
  683. } else {
  684. cooler.CoolerUseUsers = user.NickName
  685. cooler.HistoryCode = append(cooler.HistoryCode, list...)
  686. cooler.HistoryCode = cDto.UniqueSlice(cooler.HistoryCode)
  687. cooler.CoolerUserTime = model2.Time(time.Now())
  688. cooler.Status = "2" //使用结束
  689. err = e.Orm.Updates(&cooler).Where("id = ?", cooler.Id).Error
  690. if err != nil {
  691. e.Log.Errorf("保存保温箱记录失败: %s", err)
  692. return errors.New("保存保温箱记录失败")
  693. }
  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. }
  1533. // SecondaryDistribution 二次分配订单
  1534. func (e *Waybill) SecondaryDistribution(c *dto.WaybillAssignment, p *actions.DataPermission) error {
  1535. var err error
  1536. var waybillModel model.Waybill
  1537. var count int64
  1538. //查询订单是否存在
  1539. tx := e.Orm.Begin()
  1540. defer func() {
  1541. if err != nil {
  1542. tx.Rollback()
  1543. } else {
  1544. tx.Commit()
  1545. }
  1546. }()
  1547. err = tx.Scopes(actions.Permission(waybillModel.TableName(), p)).
  1548. Where("waybill_no = ?", c.WaybillNo).
  1549. First(&waybillModel).Count(&count).Error
  1550. if err != nil {
  1551. e.Log.Errorf("db error: %s", err)
  1552. if errors.Is(err, gorm.ErrRecordNotFound) {
  1553. return global.GetNotFoundOrNoPermissionErr
  1554. }
  1555. return global.GetFailedErr
  1556. }
  1557. if count == 0 {
  1558. return errors.New("订单不存在")
  1559. }
  1560. if !waybillModel.IsSecondaryDistribution {
  1561. return errors.New("该订单不允许二次分配")
  1562. }
  1563. var waybil model.Waybill
  1564. sole, err := e.CreateSole()
  1565. var no string
  1566. for {
  1567. no = time.Now().Format("200601021504") + utils.GetRandString(6, "0123456789", 0)
  1568. var j int64
  1569. err = e.Orm.Model(&waybil).Where("waybill_no = ?", no).Count(&j).Error
  1570. if err != nil {
  1571. continue
  1572. }
  1573. if j == 0 {
  1574. break
  1575. }
  1576. }
  1577. // 添加运单
  1578. waybil.WaybillNo = no
  1579. sole, err = e.CreateSole()
  1580. if err != nil {
  1581. err = errors.New("生成运单号失败")
  1582. return err
  1583. }
  1584. waybil.OrderNo = sole
  1585. waybil.Status = model.WaybillStatusInShippeds
  1586. waybil.DeptId = waybillModel.DeptId
  1587. waybil.DeliveryName = waybillModel.DeliveryName
  1588. waybil.DeliveryId = waybillModel.DeliveryId
  1589. waybil.DeliveryPhone = waybillModel.DeliveryPhone
  1590. waybil.OrderTime = model2.Time(time.Now())
  1591. c.Generate(&waybil)
  1592. err = tx.Create(&waybil).Error
  1593. if err != nil {
  1594. e.Log.Errorf("db error: %s", err)
  1595. return global.CreateFailedErr
  1596. }
  1597. // 保存发货地址
  1598. if c.SaveConsigneeAddress {
  1599. // 查询地址是否存在
  1600. address := model.Address{}
  1601. err = e.Orm.Where("address = ? and phone = ? and name = ? and dept_id = ? and address_type = 'consignee'",
  1602. c.ConsigneeAddressDetails, c.ConsigneeAddressPhone, c.ConsigneeAddressName, c.DeptId).First(&address).Error
  1603. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  1604. address.Address = c.ConsigneeAddressDetails
  1605. address.Phone = c.ConsigneeAddressPhone
  1606. address.Name = c.ConsigneeAddressName
  1607. address.DeptId = c.DeptId
  1608. address.AddressType = "consignee"
  1609. err = tx.Create(&address).Error
  1610. if err != nil {
  1611. e.Log.Errorf("创建地址失败: %s", err)
  1612. return global.CreateFailedErr
  1613. }
  1614. }
  1615. }
  1616. if len(c.Drugs) > 0 {
  1617. for _, drug := range c.Drugs {
  1618. var drugs model.Drug
  1619. drugs.WaybillNo = no
  1620. drugs.Drug_ent_base_info_id = drug.Drug_ent_base_info_id
  1621. drugs.Ent_name = drug.Ent_name
  1622. drugs.Physic_name = drug.Physic_name
  1623. drugs.Approval_licence_no = drug.Approval_licence_no
  1624. drugs.Prepn_spec = drug.Prepn_spec
  1625. drugs.Physic_type_desc = drug.Physic_type_desc
  1626. drugs.Pkg_spec_crit = drug.Pkg_spec_crit
  1627. drugs.Prepn_type_desc = drug.Prepn_type_desc
  1628. drugs.Code = drug.Code
  1629. err = tx.Save(&drugs).Error
  1630. if err != nil {
  1631. e.Log.Errorf("db error: %s", err)
  1632. return errors.New("保存药品信息失败")
  1633. }
  1634. }
  1635. }
  1636. waybillModel.ChildWaybills = append(waybillModel.ChildWaybills, waybil.WaybillNo)
  1637. err = tx.Save(&waybillModel).Error
  1638. if err != nil {
  1639. e.Log.Errorf("更新运单失败: %s", err)
  1640. return global.UpdateFailedErr
  1641. }
  1642. return nil
  1643. }