jury.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "reflect"
  7. "sort"
  8. "strconv"
  9. "time"
  10. creditMDL "go-common/app/admin/main/credit/model"
  11. "go-common/app/admin/main/credit/model/blocked"
  12. account "go-common/app/service/main/account/api"
  13. relationmdl "go-common/app/service/main/relation/model"
  14. "go-common/library/ecode"
  15. "go-common/library/log"
  16. "go-common/library/net/metadata"
  17. "go-common/library/sync/errgroup"
  18. xtime "go-common/library/time"
  19. "go-common/library/xstr"
  20. )
  21. // AddJury add jury to admin
  22. func (s *Service) AddJury(c context.Context, arg *blocked.ArgAddJurys) (err error) {
  23. arg.MIDs = creditMDL.ArrayUnique(arg.MIDs)
  24. if len(arg.MIDs) == 0 {
  25. return
  26. }
  27. items := []*blocked.Jury{}
  28. if err = s.blockedDao.ReadDB.Where("mid IN (?)", arg.MIDs).Find(&items).Error; err != nil {
  29. log.Error("s.blockedDao.juryByMIDs(%s) error(%v)", xstr.JoinInts(arg.MIDs), err)
  30. err = nil
  31. }
  32. mids := make(map[int64]*blocked.Jury, len(arg.MIDs))
  33. for _, v := range items {
  34. mids[v.UID] = v
  35. }
  36. day, _ := time.ParseDuration("24h")
  37. users := make([]*blocked.Jury, 0, len(arg.MIDs))
  38. tx := s.DB.Begin()
  39. defer func() {
  40. if err != nil {
  41. tx.Rollback()
  42. } else {
  43. tx.Commit()
  44. }
  45. }()
  46. now := time.Now()
  47. var multiple []interface{}
  48. for _, mid := range arg.MIDs {
  49. user := &blocked.Jury{
  50. UID: mid,
  51. Status: blocked.JuryStatusOn,
  52. OPID: arg.OPID,
  53. Remark: blocked.AddJuryRemark,
  54. Expired: xtime.Time(now.Add(day * time.Duration(arg.Day)).Unix()),
  55. }
  56. if jury, ok := mids[mid]; ok {
  57. user.ID = jury.ID
  58. switch {
  59. case jury.Black == blocked.JuryBlack:
  60. continue
  61. case jury.Black == blocked.JuryWhite:
  62. user.Black = blocked.JuryWhite
  63. }
  64. user.CTime = jury.CTime
  65. user.VoteTotal = jury.VoteTotal
  66. user.VoteRight = jury.VoteRight
  67. user.Total = jury.Total
  68. single := map[string]interface{}{
  69. "id": jury.ID,
  70. "oper_id": arg.OPID,
  71. "status": blocked.JuryStatusOn,
  72. "black": user.Black,
  73. "expired": now.Add(day * time.Duration(arg.Day)).Format(creditMDL.TimeFormatSec),
  74. }
  75. multiple = append(multiple, single)
  76. }
  77. if err = tx.Save(&user).Error; err != nil {
  78. log.Error("s.DB.Create error(%v)", err)
  79. return
  80. }
  81. s.AddNotify(func() {
  82. s.Search.SearchUpdate(context.TODO(), blocked.BusinessBlockedJury, blocked.TableBlockedJury, multiple)
  83. })
  84. users = append(users, user)
  85. }
  86. if arg.Send == blocked.NeedSendMsg {
  87. for _, u := range users {
  88. msg := &blocked.SysMsg{
  89. Type: blocked.MsgTypeGetJuryer,
  90. MID: u.UID,
  91. Day: arg.Day,
  92. RemoteIP: metadata.String(c, metadata.RemoteIP),
  93. }
  94. s.MsgCh <- msg
  95. }
  96. }
  97. return
  98. }
  99. // Cases deal case data.
  100. func (s *Service) Cases(c context.Context, arg *blocked.ArgCaseSearch) (list []*blocked.Case, pager *blocked.Pager, err error) {
  101. var ids []int64
  102. ids, pager, err = s.searchDao.Case(c, arg)
  103. if err != nil {
  104. log.Error(" s.searchDao.Case error(%v)", err)
  105. return
  106. }
  107. if len(ids) == 0 {
  108. return
  109. }
  110. var (
  111. accInfoMap map[int64]*account.Info
  112. relationsMap map[int64]*relationmdl.Stat
  113. uids = make([]int64, 0)
  114. )
  115. ids = creditMDL.ArrayUnique(ids)
  116. if err = s.blockedDao.ReadDB.Where("id IN (?)", ids).Order(fmt.Sprintf("%s %s", arg.Order, arg.Sort)).Find(&list).Error; err != nil {
  117. if err != ecode.NothingFound {
  118. log.Error("s.blockedDao(%s) error(%v)", xstr.JoinInts(ids), err)
  119. return
  120. }
  121. log.Warn("search ids(%s) not in db", xstr.JoinInts(ids))
  122. err = nil
  123. }
  124. for _, v := range list {
  125. if v.MID > 0 {
  126. uids = append(uids, v.MID)
  127. }
  128. }
  129. if accInfoMap, err = s.accDao.RPCInfos(c, uids); err != nil {
  130. log.Error("s.accDao.RPCInfos(%s) error(%v)", xstr.JoinInts(uids), err)
  131. err = nil
  132. }
  133. if relationsMap, err = s.RelationDao.RPCStats(c, uids); err != nil {
  134. log.Error("s.RelationDao.RPCStats(%s) error(%v)", xstr.JoinInts(uids), err)
  135. err = nil
  136. }
  137. for _, v := range list {
  138. if accInfo, ok := accInfoMap[v.MID]; ok {
  139. v.Uname = accInfo.Name
  140. }
  141. if relationInfo, ok := relationsMap[v.MID]; ok {
  142. v.Fans = relationInfo.Follower
  143. }
  144. v.OPName = s.Managers[v.OPID]
  145. v.StatusDesc = blocked.StatusDesc[v.Status]
  146. v.OriginTypeDesc = blocked.OriginTypeDesc[v.OriginType]
  147. v.ReasonTypeDesc = blocked.ReasonTypeDesc(v.ReasonType)
  148. v.PunishDesc = blocked.PunishDesc[v.PunishResult]
  149. v.CaseTypeDesc = blocked.CaseTypeDesc[v.CaseType]
  150. v.VoteTotal = blocked.VoteTotal(v.VoteRule, v.VoteBreak, v.VoteDelete)
  151. if v.VoteRule > 0 || v.VoteBreak > 0 || v.VoteDelete > 0 {
  152. v.BlockedPercent = blocked.BreakPercent(v.VoteRule, v.VoteBreak, v.VoteDelete)
  153. v.DeletePercent = blocked.DeletePercent(v.VoteRule, v.VoteBreak, v.VoteDelete)
  154. v.RulePercent = blocked.RulePercent(v.VoteRule, v.VoteBreak, v.VoteDelete)
  155. }
  156. }
  157. return
  158. }
  159. // Opinions is block opinions
  160. func (s *Service) Opinions(c context.Context, arg *blocked.ArgOpinionSearch) (list []*blocked.Opinion, pager *blocked.Pager, err error) {
  161. var ids []int64
  162. ids, pager, err = s.searchDao.Opinion(c, arg)
  163. if err != nil {
  164. log.Error("s.blockedDao.Search appid(%s) error(%v)", "", err)
  165. return
  166. }
  167. if len(ids) == 0 {
  168. return
  169. }
  170. var (
  171. accInfoMap map[int64]*account.Info
  172. relationsMap map[int64]*relationmdl.Stat
  173. uids = make([]int64, 0)
  174. )
  175. ids = creditMDL.ArrayUnique(ids)
  176. if err = s.blockedDao.ReadDB.Where("id IN (?)", ids).Order(fmt.Sprintf("%s %s", arg.Order, arg.Sort)).Find(&list).Error; err != nil {
  177. if err != ecode.NothingFound {
  178. log.Error("s.blockedDao(%s) error(%v)", xstr.JoinInts(ids), err)
  179. return
  180. }
  181. log.Warn("search ids(%s) not in db", xstr.JoinInts(ids))
  182. err = nil
  183. }
  184. for _, v := range list {
  185. if v.MID > 0 {
  186. uids = append(uids, v.MID)
  187. }
  188. }
  189. accInfoMap, err = s.accDao.RPCInfos(c, uids)
  190. if err != nil {
  191. log.Error("s.accDao.RPCInfos error(%v)", err)
  192. err = nil
  193. }
  194. if relationsMap, err = s.RelationDao.RPCStats(c, uids); err != nil {
  195. log.Error("s.RelationDao.RPCStats(%s) error(%v)", xstr.JoinInts(uids), err)
  196. err = nil
  197. }
  198. for _, v := range list {
  199. if opinion, ok := accInfoMap[v.MID]; ok {
  200. v.UName = opinion.Name
  201. }
  202. if relationInfo, ok := relationsMap[v.MID]; ok {
  203. v.Fans = relationInfo.Follower
  204. }
  205. v.OPName = s.Managers[v.OperID]
  206. v.AttrDesc = blocked.AttrDesc[v.Attr]
  207. v.VoteDesc = blocked.VoteDesc[v.Vote]
  208. v.VoteStateDesc = blocked.VoteStateDesc[v.State]
  209. }
  210. return
  211. }
  212. // Jurys select jury lists.
  213. func (s *Service) Jurys(c context.Context, arg *blocked.ArgJurySearch) (list []*blocked.Jury, pager *blocked.Pager, err error) {
  214. var ids []int64
  215. ids, pager, err = s.searchDao.Jury(c, arg)
  216. if err != nil {
  217. log.Error("s.searchDao.Jury error(%v)", err)
  218. return
  219. }
  220. if len(ids) == 0 {
  221. return
  222. }
  223. var (
  224. accInfoMap map[int64]*account.Info
  225. uids = make([]int64, len(ids))
  226. )
  227. ids = creditMDL.ArrayUnique(ids)
  228. if err = s.blockedDao.ReadDB.Where("id IN (?)", ids).Order(fmt.Sprintf("%s %s", arg.Order, arg.Sort)).Find(&list).Error; err != nil {
  229. if err != ecode.NothingFound {
  230. log.Error("s.blockedDao(%s) error(%v)", xstr.JoinInts(ids), err)
  231. return
  232. }
  233. log.Warn("search ids(%s) not in db", xstr.JoinInts(ids))
  234. err = nil
  235. }
  236. for _, v := range list {
  237. uids = append(uids, v.UID)
  238. }
  239. accInfoMap, err = s.accDao.RPCInfos(c, uids)
  240. if err != nil {
  241. log.Error("s.accDao.RPCInfos error(%v)", err)
  242. err = nil
  243. }
  244. for _, v := range list {
  245. if jury, ok := accInfoMap[v.UID]; ok {
  246. v.UName = jury.Name
  247. }
  248. v.OPName = s.Managers[v.OPID]
  249. v.EffectDay = xtime.Time(v.Expired.Time().AddDate(0, 0, -blocked.JuryDay).Unix())
  250. if v.EffectDay < v.CTime {
  251. v.EffectDay = v.CTime
  252. }
  253. if v.VoteTotal > 0 {
  254. v.VoteRadio = strconv.FormatFloat(float64(v.VoteRight)/float64(v.VoteTotal)*100, 'f', 2, 64)
  255. } else {
  256. v.VoteRadio = "-1"
  257. }
  258. v.StatusDesc = blocked.JuryerStatus[v.Status]
  259. v.BlackDesc = blocked.JuryerStyle[v.Black]
  260. }
  261. return
  262. }
  263. // JurysEx export jury list.
  264. func (s *Service) JurysEx(c context.Context, arg *blocked.ArgJurySearch) (list []*blocked.Jury, err error) {
  265. var (
  266. ps = 500
  267. count int
  268. pager *blocked.Pager
  269. g errgroup.Group
  270. )
  271. if list, pager, err = s.Jurys(c, arg); err != nil {
  272. log.Error("s.Infos(%+v) error(%v)", arg, err)
  273. return
  274. }
  275. if pager == nil {
  276. log.Warn("arg(%+v) jury search data empty!", arg)
  277. return
  278. }
  279. count = pager.Total / ps
  280. if pager.Total%ps != 0 {
  281. count++
  282. }
  283. lCh := make(chan []*blocked.Jury, count)
  284. for pn := 1; pn <= count; pn++ {
  285. tmpPn := pn
  286. g.Go(func() (err error) {
  287. var gJury []*blocked.Jury
  288. gArg := &blocked.ArgJurySearch{
  289. UID: arg.UID,
  290. Status: arg.Status,
  291. Black: arg.Black,
  292. ExpiredFrom: arg.ExpiredFrom,
  293. ExpiredTo: arg.ExpiredTo,
  294. Order: arg.Order,
  295. Sort: arg.Sort,
  296. PN: tmpPn,
  297. PS: ps,
  298. }
  299. gJury, _, err = s.Jurys(c, gArg)
  300. if err != nil {
  301. log.Error("s.Jurys(%+v) error(%v)", gJury, err)
  302. err = nil
  303. return
  304. }
  305. lCh <- gJury
  306. return
  307. })
  308. }
  309. g.Wait()
  310. close(lCh)
  311. for jInfo := range lCh {
  312. list = append(list, jInfo...)
  313. }
  314. sort.Slice(list, func(i int, j int) bool {
  315. return list[i].ID < list[j].ID
  316. })
  317. return
  318. }
  319. // UpCaseStatus update case status.
  320. func (s *Service) UpCaseStatus(c context.Context, arg *blocked.ArgUpStatus) (err error) {
  321. items := []blocked.Case{}
  322. if err = s.blockedDao.ReadDB.Where("id IN(?)", arg.IDS).Find(&items).Error; err != nil {
  323. log.Error("s.blockedDao.caseByIDs(%s) error(%v)", xstr.JoinInts(arg.IDS), err)
  324. return
  325. }
  326. var multiple []interface{}
  327. if arg.Status == blocked.CaseStatusGranting {
  328. hour := s.CaseConfig(blocked.ConfigCaseGiveHours)
  329. now := time.Now()
  330. if err = s.DB.Model(blocked.Case{}).Where("id IN(?)", arg.IDS).Updates(
  331. &blocked.Case{
  332. Status: arg.Status,
  333. OPID: arg.OID,
  334. StartTime: xtime.Time(now.Unix()),
  335. EndTime: xtime.Time(now.Add(time.Duration(hour) * time.Hour).Unix()),
  336. }).Error; err != nil {
  337. return
  338. }
  339. for _, item := range items {
  340. single := map[string]interface{}{
  341. "id": item.ID,
  342. "oper_id": arg.OID,
  343. "start_time": now.Format(creditMDL.TimeFormatSec),
  344. "status": arg.Status,
  345. "case_type": item.CaseType,
  346. }
  347. multiple = append(multiple, single)
  348. }
  349. } else {
  350. if err = s.DB.Model(blocked.Case{}).Where("id IN(?)", arg.IDS).Updates(
  351. &blocked.Case{
  352. Status: arg.Status,
  353. OPID: arg.OID,
  354. }).Error; err != nil {
  355. return
  356. }
  357. for _, item := range items {
  358. single := map[string]interface{}{
  359. "id": item.ID,
  360. "oper_id": arg.OID,
  361. "status": arg.Status,
  362. "case_type": item.CaseType,
  363. }
  364. multiple = append(multiple, single)
  365. }
  366. }
  367. s.AddNotify(func() {
  368. s.Search.SearchUpdate(context.TODO(), blocked.BusinessBlockedCase, blocked.TableBlockedCase, multiple)
  369. })
  370. return
  371. }
  372. // CaseReason reason info.
  373. func (s *Service) CaseReason(c context.Context) (cr map[int]string, err error) {
  374. var reason []*blocked.Reason
  375. cr = make(map[int]string)
  376. if err = s.ReadDB.Select([]string{"id", "reason"}).Where("status = 0").Find(&reason).Error; err != nil {
  377. if err == ecode.NothingFound {
  378. err = nil
  379. return
  380. }
  381. return
  382. }
  383. for _, v := range reason {
  384. cr[v.ID] = v.Reason
  385. }
  386. return
  387. }
  388. // CaseConf caseconfig list.
  389. func (s *Service) CaseConf(c context.Context) (cc map[string]string, err error) {
  390. var configs []*blocked.Config
  391. cc = make(map[string]string)
  392. err = s.ReadDB.Select([]string{"config_key", "content"}).Find(&configs).Error
  393. if err != nil || configs == nil {
  394. return
  395. }
  396. for _, v := range configs {
  397. cc[v.ConfigKey] = v.Content
  398. }
  399. return
  400. }
  401. // SetCaseConf update case config.
  402. func (s *Service) SetCaseConf(c context.Context, cc *blocked.ArgCaseConf) (err error) {
  403. v := reflect.ValueOf(cc).Elem()
  404. tx := s.DB.Begin()
  405. defer func() {
  406. if err != nil {
  407. tx.Rollback()
  408. } else {
  409. tx.Commit()
  410. }
  411. }()
  412. for i := 0; i < v.NumField(); i++ {
  413. fieldValue := strconv.Itoa(v.Field(i).Interface().(int))
  414. tag := v.Type().Field(i).Tag.Get("form")
  415. if err = tx.Model(&blocked.Config{}).Where("config_key = ?", tag).Updates(map[string]interface{}{"content": fieldValue, "oper_id": cc.OID}).Error; err != nil {
  416. log.Error("caseConfig(%s,%d) update error(%v)", v.Field(i).Type().Name(), v.Field(i).Interface().(int64), err)
  417. return
  418. }
  419. }
  420. return
  421. }
  422. // CaseConfig get config by key.
  423. func (s *Service) CaseConfig(ck string) (cv int64) {
  424. if v, ok := s.caseConfCache[ck]; ok {
  425. cv, _ = strconv.ParseInt(v, 10, 64)
  426. }
  427. return
  428. }
  429. // KPIPoint get kpi_point data
  430. func (s *Service) KPIPoint(c context.Context, arg *blocked.ArgKpiPointSearch) (list []*blocked.KPIPoint, pager *blocked.Pager, err error) {
  431. var ids []int64
  432. ids, pager, err = s.searchDao.KPIPoint(c, arg)
  433. if err != nil {
  434. log.Error("s.searchDao.KPIPoint error (%v)", err)
  435. return
  436. }
  437. if len(ids) == 0 {
  438. return
  439. }
  440. ids = creditMDL.ArrayUnique(ids)
  441. if err = s.blockedDao.ReadDB.Where("id IN (?)", ids).Order(fmt.Sprintf("%s %s", arg.Order, arg.Sort)).Find(&list).Error; err != nil {
  442. if err != ecode.NothingFound {
  443. log.Error("s.blockedDao(%s) error(%v)", xstr.JoinInts(ids), err)
  444. return
  445. }
  446. log.Warn("search ids(%s) not in db", xstr.JoinInts(ids))
  447. err = nil
  448. }
  449. return
  450. }
  451. // VotenumConf votenumConf list.
  452. func (s *Service) VotenumConf(c context.Context) (cc string, err error) {
  453. var bc = &blocked.Config{}
  454. err = s.ReadDB.Select("content").Where("config_key = 'vote_num'").Find(&bc).Error
  455. if err != nil || bc.Content == "" {
  456. log.Error("s.VotenumConf(%s) error(%v)", cc, err)
  457. return
  458. }
  459. cc = bc.Content
  460. return
  461. }
  462. // SetVotenumConf .
  463. func (s *Service) SetVotenumConf(c context.Context, vn *blocked.ArgVoteNum) (err error) {
  464. v := blocked.VoteNum{}
  465. v.RateS = vn.RateS
  466. v.RateA = vn.RateA
  467. v.RateB = vn.RateB
  468. v.RateC = vn.RateC
  469. v.RateD = vn.RateD
  470. vnb, err := json.Marshal(v)
  471. if err != nil {
  472. log.Error("json.Marshal(%+v) error(%v)", v, err)
  473. }
  474. config := &blocked.Config{}
  475. s.ReadDB.Where("config_key = 'vote_num'").Find(config)
  476. var vconfig *blocked.Config
  477. if config != nil && config.ID != 0 {
  478. vconfig = &blocked.Config{
  479. ID: config.ID,
  480. ConfigKey: "vote_num",
  481. Content: string(vnb),
  482. OperID: vn.OID,
  483. }
  484. } else {
  485. vconfig = &blocked.Config{
  486. ConfigKey: "vote_num",
  487. Content: string(vnb),
  488. OperID: vn.OID,
  489. }
  490. }
  491. if err = s.DB.Save(&vconfig).Error; err != nil {
  492. log.Error("http.setAutoCaseConfig error(%v)", err)
  493. return
  494. }
  495. return
  496. }
  497. // WebHook a webhook from work flow.
  498. func (s *Service) WebHook(c context.Context, data []byte) (err error) {
  499. wh := &blocked.WebHook{}
  500. if err = json.Unmarshal(data, &wh); err != nil {
  501. err = ecode.RequestErr
  502. log.Error("webhook json rawmessage(%s) error(%v)", string(data), err)
  503. return
  504. }
  505. if wh.Verb == "chall.SetResult" || wh.Verb == "chall.BatchSetResult" {
  506. if wh.Target == nil || wh.Object == nil {
  507. log.Warn("wh.Target or wh.Object is nil %v,%v", wh.Target, wh.Object)
  508. return
  509. }
  510. // appeal state not changed .
  511. if wh.Target.State == wh.Object.State {
  512. log.Warn("appeal state not changed target=%d object=%d", wh.Target.State, wh.Object.State)
  513. return
  514. }
  515. switch wh.Object.State {
  516. case blocked.AppealStateSucc:
  517. if err = s.blockedDao.DB.Model(&blocked.Info{}).Where("case_id =?", wh.Target.OID).Update("status", blocked.BlockStateClose).Error; err != nil {
  518. log.Error("s.blockedDao.DB error(%v)", err)
  519. return
  520. }
  521. s.MsgCh <- &blocked.SysMsg{Type: blocked.MsgTypeAppealSucc, MID: wh.Target.Mid, CID: wh.Target.OID, RemoteIP: metadata.String(c, metadata.RemoteIP)}
  522. case blocked.AppealStateFail:
  523. s.MsgCh <- &blocked.SysMsg{Type: blocked.MsgTypeAppealFail, MID: wh.Target.Mid, CID: wh.Target.OID, RemoteIP: metadata.String(c, metadata.RemoteIP)}
  524. default:
  525. log.Warn("unknown webhook state(%d) ", wh.Object.State)
  526. }
  527. }
  528. return
  529. }