public.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. package p
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "reflect"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. . "app.yhyue.com/moapp/jybase/common"
  13. util "app.yhyue.com/moapp/jybase/common"
  14. . "app.yhyue.com/moapp/jybase/date"
  15. "app.yhyue.com/moapp/jybase/es"
  16. "app.yhyue.com/moapp/jybase/logger"
  17. . "app.yhyue.com/moapp/jybase/mongodb"
  18. . "app.yhyue.com/moapp/jybase/mysql"
  19. "app.yhyue.com/moapp/jybase/redis"
  20. rcDb "bp.jydev.jianyu360.cn/BaseService/resourceCenter/public/db"
  21. rcService "bp.jydev.jianyu360.cn/BaseService/resourceCenter/public/service"
  22. . "bp.jydev.jianyu360.cn/BaseService/userCenter/identity"
  23. "jygit.jydev.jianyu360.cn/BaseService/ossClient"
  24. "jygit.jydev.jianyu360.cn/BaseService/ossClient/entity"
  25. )
  26. // 金额转化 金额:0-万元以下单位为元 ,万元以上至亿元以下单位为万元 ,亿元以上单位为亿元。保留 小数点后 2 位,不进行四舍五入。
  27. func ConversionMoney(i_money interface{}) string {
  28. m := ""
  29. if reflect.TypeOf(i_money).Name() == "float64" {
  30. m = strconv.FormatFloat(Float64All(i_money), 'f', -1, 64)
  31. } else {
  32. m = ObjToString(i_money)
  33. }
  34. if m == "" {
  35. return m
  36. }
  37. m_arr := strings.Split(m, ".")
  38. m_1 := m_arr[0]
  39. len_m1 := len([]rune(m_1))
  40. if len_m1 >= 9 {
  41. m = m_1[0:len_m1-8] + "." + m_1[len_m1-8:len_m1-6] + "亿元"
  42. } else if len_m1 >= 5 {
  43. m = m_1[0:len_m1-4] + "." + m_1[len_m1-4:len_m1-2] + "万元"
  44. } else {
  45. if len(m_arr) == 1 {
  46. return m + ".00元"
  47. }
  48. m_2 := m_arr[1]
  49. if len([]rune(m_2)) > 1 {
  50. m_2 = m_2[0:2]
  51. } else {
  52. m_2 = m_2[0:1] + "0"
  53. }
  54. m = m_1 + "." + m_2 + "元"
  55. }
  56. return m
  57. }
  58. // 微信模板消息 remark
  59. func WxTplRemark(titles []string, lastTime int64, hasLen int) string {
  60. tip := ""
  61. second := time.Now().Unix() - lastTime
  62. if second > 0 {
  63. if second < 61 {
  64. tip = fmt.Sprintf("%d秒前发布的:\n", second)
  65. } else {
  66. second = second / 60
  67. if second < 121 {
  68. if second < 1 {
  69. second = 1
  70. }
  71. tip = fmt.Sprintf("%d分钟前发布的:\n", second)
  72. }
  73. }
  74. }
  75. lastTip := ""
  76. if len(titles) > 1 {
  77. lastTip = fmt.Sprintf("...(共%d条)", len(titles))
  78. }
  79. reLen := 199 - hasLen - len([]rune(tip))
  80. lastTipLen := len([]rune(lastTip))
  81. wxTplMsgTitle := ""
  82. bshow := false
  83. for n := 1; n < len(titles)+1; n++ {
  84. curTitle := titles[n-1]
  85. tmptitle := wxTplMsgTitle + fmt.Sprintf("%d %s\n", n, curTitle)
  86. ch := reLen - len([]rune(tmptitle))
  87. if ch < lastTipLen { //加上后大于后辍,则没有完全显示
  88. if ch == 0 && n == len(titles) {
  89. wxTplMsgTitle = tmptitle
  90. bshow = true
  91. } else {
  92. ch_1 := reLen - len([]rune(wxTplMsgTitle)) - lastTipLen
  93. if ch_1 > 8 {
  94. curLen := len([]rune(curTitle))
  95. if ch_1 > curLen {
  96. ch_1 = curLen
  97. }
  98. wxTplMsgTitle += fmt.Sprintf("%d %s\n", n, string([]rune(curTitle)[:ch_1-3]))
  99. }
  100. }
  101. } else {
  102. wxTplMsgTitle = tmptitle
  103. if n == len(titles) {
  104. bshow = true
  105. }
  106. }
  107. }
  108. if bshow {
  109. lastTip = ""
  110. }
  111. return tip + wxTplMsgTitle + lastTip
  112. }
  113. // 获取信息行业
  114. func GetSubScopeClass(subscopeclass interface{}) string {
  115. industry := ""
  116. if subscopeclass != nil {
  117. k2sub := strings.Split(ObjToString(subscopeclass), ",")
  118. if len(k2sub) > 0 {
  119. industry = k2sub[0]
  120. if industry != "" {
  121. ss := strings.Split(industry, "_")
  122. if len(ss) > 1 {
  123. industry = ss[0]
  124. }
  125. }
  126. }
  127. }
  128. return industry
  129. }
  130. // 控制一分钟最大推送数,均匀调度
  131. func LimitMaxOneMinutePush(pushPoll *chan bool, maxOneMinute int) {
  132. max := int(maxOneMinute / 60)
  133. *pushPoll = make(chan bool, max)
  134. go func() {
  135. for {
  136. time.Sleep(time.Second)
  137. for i := 0; i < max; i++ {
  138. select {
  139. case *pushPoll <- true:
  140. default:
  141. continue
  142. }
  143. }
  144. }
  145. }()
  146. }
  147. func UpdateUserIsPush(Mgo *MongodbSim, userId string, err error) {
  148. if err == nil {
  149. return
  150. }
  151. if strings.Contains(err.Error(), "[43004]") {
  152. Mgo.UpdateById("user", userId, map[string]interface{}{
  153. "$set": map[string]interface{}{
  154. "i_ispush": 0,
  155. },
  156. })
  157. }
  158. }
  159. // 查找我的子账号
  160. func MySonAccounts(Mgo *MongodbSim, coll, userId string, field map[string]interface{}) *[]map[string]interface{} {
  161. users, _ := Mgo.Find(coll, map[string]interface{}{
  162. "i_member_sub_status": 1,
  163. "s_member_mainid": userId,
  164. "i_member_status": map[string]interface{}{"$gt": 0},
  165. }, nil, field, false, -1, -1)
  166. if users == nil {
  167. users = &[]map[string]interface{}{}
  168. }
  169. return users
  170. }
  171. // 是否购买此服务
  172. func HasService(msl *Mysql, userId string, params ...int) *MemberService {
  173. args := []interface{}{}
  174. ws := []string{}
  175. for _, v := range params {
  176. args = append(args, v)
  177. ws = append(ws, "?")
  178. }
  179. args = append(args, args...)
  180. args = append(args, userId, NowFormat(Date_Full_Layout))
  181. list := msl.SelectBySql(`SELECT a.l_starttime,b.id from jianyu.bigmember_service_user a
  182. INNER JOIN jianyu.bigmember_service b on (((b.id in (`+strings.Join(ws, ",")+`) and a.s_serviceid=b.id) or (b.i_pid in (`+strings.Join(ws, ",")+`) and a.s_serviceid=b.i_pid)) and b.i_status=0 and a.s_userid=? and a.i_status=0 and a.l_endtime>?)`, args...)
  183. ms := &MemberService{
  184. Services: map[int]*memberService{},
  185. }
  186. if list != nil {
  187. for _, v := range *list {
  188. ms.IsBuy = true
  189. id := util.IntAll(v["id"])
  190. ms.Services[id] = &memberService{
  191. Id: id,
  192. StartTime: util.ObjToString(v["l_starttime"]),
  193. }
  194. }
  195. }
  196. return ms
  197. }
  198. func GetInfoTitle(info map[string]interface{}) string {
  199. title, _ := info["title"].(string)
  200. jsondata, _ := info["jsondata"].(map[string]interface{})
  201. if jsondata != nil {
  202. goods, _ := jsondata["goods"].(string)
  203. title += goods
  204. }
  205. title = strings.ToUpper(title)
  206. return title
  207. }
  208. // 加载数据到内存中
  209. func LoadBidding(mgo *MongodbSim, dbName, coll, incField string, startTime, maxSize int64, redisCache bool, query, fields map[string]interface{}, ossAddr string) (*[]map[string]interface{}, int64) {
  210. defer util.Catch()
  211. endTime := time.Now().Unix()
  212. if query == nil || len(query) == 0 {
  213. query = map[string]interface{}{
  214. incField: map[string]interface{}{
  215. "$gte": startTime,
  216. "$lt": endTime,
  217. },
  218. }
  219. }
  220. logger.Info("开始加载", coll, "数据", query)
  221. queryField := map[string]interface{}{
  222. "title": 1,
  223. "detail": 1,
  224. "purchasing": 1,
  225. "projectname": 1,
  226. "projectcode": 1,
  227. "buyer": 1,
  228. "buyerperson": 1,
  229. "buyertel": 1,
  230. "s_winner": 1,
  231. "agency": 1,
  232. "bidopentime": 1,
  233. "projectscope": 1,
  234. "publishtime": 1,
  235. "toptype": 1,
  236. "subtype": 1,
  237. "area": 1,
  238. "s_subscopeclass": 1,
  239. "city": 1,
  240. "district": 1,
  241. "buyerclass": 1,
  242. "jsondata": 1,
  243. "budget": 1,
  244. "bidamount": 1,
  245. "isValidFile": 1,
  246. "site": 1,
  247. "agencyperson": 1,
  248. "agencytel": 1,
  249. "winnerperson": 1,
  250. "winnertel": 1,
  251. "signendtime": 1,
  252. "bidendtime": 1,
  253. "entidlist": 1,
  254. "autoid": 1,
  255. }
  256. if fields != nil {
  257. for k, v := range fields {
  258. if util.IntAll(v) == 0 {
  259. delete(queryField, k)
  260. } else {
  261. queryField[k] = v
  262. }
  263. }
  264. }
  265. var res []map[string]interface{}
  266. sess := mgo.GetMgoConn()
  267. defer mgo.DestoryMongoConn(sess)
  268. it := sess.DB(dbName).C(coll).Find(query).Select(queryField).Iter()
  269. var index int64
  270. for temp := make(map[string]interface{}); it.Next(&temp); {
  271. _id := BsonIdToSId(temp["_id"])
  272. if publishtime := util.Int64All(temp["publishtime"]); startTime-publishtime > 7*86400 {
  273. logger.Info(_id, "发布时间大于7天,不参与匹配", startTime, publishtime)
  274. continue
  275. }
  276. temp["_id"] = _id
  277. title, _ := temp["title"].(string)
  278. title = strings.ReplaceAll(title, "\n", "")
  279. temp["title"] = title
  280. if util.ObjToString(temp["area"]) == "A" {
  281. temp["area"] = "全国"
  282. }
  283. temp["attachment_count"] = GetAttachmentCount(temp)
  284. res = append(res, temp)
  285. index++
  286. if index%500 == 0 {
  287. logger.Info("加载", coll, "数据:", index)
  288. }
  289. if maxSize > 0 && index == maxSize {
  290. break
  291. }
  292. }
  293. if util.IntAll(queryField["detail"]) > 0 {
  294. for _, temp := range res {
  295. _id := ObjToString(temp["_id"])
  296. if util.ObjToString(temp["detail"]) == "" && ossAddr != "" {
  297. if repl, err := ossClient.GetBidDetailByGrpc(ossAddr, &entity.Args{"detail", _id}); err == nil {
  298. temp["detail"] = repl.Data
  299. } else {
  300. logger.Error(_id, "获取正文出错", err)
  301. }
  302. }
  303. if redisCache {
  304. //信息缓存3天
  305. info := map[string]interface{}{}
  306. for _, v := range SaveBiddingField {
  307. if v == "_id" || temp[v] == nil {
  308. continue
  309. }
  310. info[v] = temp[v]
  311. }
  312. if temp["detail"] != nil {
  313. info["detail"] = temp["detail"]
  314. }
  315. redis.Put(Pushcache_1, "info_"+_id, info, OneDaySecond)
  316. }
  317. }
  318. }
  319. if util.IntAll(queryField["filetext"]) > 0 {
  320. BiddingRepair(res, "filetext")
  321. }
  322. logger.Info(coll, "数据已经加载结束。。。", index)
  323. return &res, endTime
  324. }
  325. func BiddingRepair(res []map[string]interface{}, fields string) {
  326. array := []map[string]interface{}{}
  327. for _, v := range res {
  328. array = append(array, v)
  329. if len(array) == 50 {
  330. OnceBiddingRepair(array, fields)
  331. array = []map[string]interface{}{}
  332. }
  333. }
  334. if len(array) > 0 {
  335. OnceBiddingRepair(array, fields)
  336. array = []map[string]interface{}{}
  337. }
  338. }
  339. func OnceBiddingRepair(array []map[string]interface{}, fields string) {
  340. if es.VarEs == nil {
  341. return
  342. }
  343. ids := []string{}
  344. for _, v := range array {
  345. ids = append(ids, fmt.Sprintf(`"%s"`, util.ObjToString(v["_id"])))
  346. }
  347. m := map[string]map[string]interface{}{}
  348. list := es.VarEs.Get(Es_Bidding, Es_Bidding, fmt.Sprintf(Es_Query_By_Ids, strings.Join(ids, ","), fields, len(ids)))
  349. if list == nil {
  350. return
  351. }
  352. for _, v := range *list {
  353. m[util.ObjToString(v["_id"])] = v
  354. }
  355. for _, v := range array {
  356. obj := m[util.ObjToString(v["_id"])]
  357. if obj == nil {
  358. continue
  359. }
  360. for kk, vv := range obj {
  361. v[kk] = vv
  362. }
  363. }
  364. }
  365. func ToSortList(list interface{}) *SortList {
  366. sl := make(SortList, 0)
  367. if list == nil {
  368. return &sl
  369. }
  370. b, err := json.Marshal(list)
  371. if err != nil {
  372. return &sl
  373. }
  374. err = json.Unmarshal(b, &sl)
  375. if err != nil {
  376. return &sl
  377. }
  378. sort.Sort(sl)
  379. return &sl
  380. }
  381. // 第一个参数是老数据,第二个参数是新进数据
  382. func MergeSortList(o, n interface{}, maxPushSize int) *SortList {
  383. of, oo := o.(*SortList)
  384. if !oo {
  385. of = ToSortList(o)
  386. }
  387. nf, no := n.(*SortList)
  388. if !no {
  389. nf = ToSortList(n)
  390. }
  391. idMap := map[string]bool{}
  392. for _, v := range *nf {
  393. idMap[util.ObjToString(v.Info["_id"])] = true
  394. }
  395. for _, v := range *of {
  396. if idMap[util.ObjToString(v.Info["_id"])] {
  397. continue
  398. }
  399. *nf = append(*nf, v)
  400. }
  401. sort.Sort(nf)
  402. if maxPushSize > 0 && len(*nf) > maxPushSize {
  403. *nf = (*nf)[:maxPushSize]
  404. }
  405. return nf
  406. }
  407. // 获取招标信息附件数量
  408. func GetAttachmentCount(temp map[string]interface{}) int {
  409. isValidFile, _ := temp["isValidFile"].(bool)
  410. if isValidFile {
  411. return 1
  412. }
  413. return 0
  414. }
  415. // 获取招标信息附件数量
  416. func GetAttachmentCountById(mgo *MongodbSim, dbName, coll, _id string) int {
  417. sess := mgo.GetMgoConn()
  418. defer mgo.DestoryMongoConn(sess)
  419. temp := map[string]interface{}{}
  420. sess.DB(dbName).C(coll).Find(map[string]interface{}{
  421. "_id": StringTOBsonId(_id),
  422. }).Select(map[string]interface{}{
  423. "isValidFile": 1,
  424. }).One(&temp)
  425. if temp != nil {
  426. return GetAttachmentCount(temp)
  427. }
  428. return -1
  429. }
  430. func NewBiddingInfo(info map[string]interface{}, keys []string) *BiddingInfo {
  431. bi := &BiddingInfo{}
  432. bi.Title, _ = info["title"].(string)
  433. bi.ClearTitle = TitleClearRe.ReplaceAllString(strings.Replace(bi.Title, "\n", "", -1), "$1")
  434. bi.Area, _ = info["area"].(string)
  435. if bi.Area == "A" {
  436. bi.Area = "全国"
  437. }
  438. bi.AreaTitle = fmt.Sprintf("[%s]%s", bi.Area, bi.ClearTitle)
  439. bi.Publishtime = util.Int64All(info["publishtime"])
  440. bi.PublishtimeYMD = FormatDateByInt64(&bi.Publishtime, Date_Short_Layout)
  441. bi.PublishtimeDiff = util.TimeDiff(time.Unix(bi.Publishtime, 0))
  442. bi.Buyerclass, _ = info["buyerclass"].(string)
  443. bi.Subscopeclass = GetSubScopeClass(info["s_subscopeclass"])
  444. bi.Bidamount = info["bidamount"]
  445. bi.Budget = info["budget"]
  446. if bi.Bidamount != nil {
  447. bi.Acount = ConversionMoney(bi.Bidamount)
  448. } else if bi.Budget != nil {
  449. bi.Acount = ConversionMoney(bi.Budget)
  450. }
  451. bi.Id, _ = info["_id"].(string)
  452. bi.AutoId = Int64All(info["autoid"])
  453. bi.Subtype, _ = info["subtype"].(string)
  454. bi.Toptype, _ = info["toptype"].(string)
  455. bi.Infotype = bi.Subtype
  456. if bi.Infotype == "" {
  457. bi.Infotype = bi.Toptype
  458. }
  459. bi.HighlightTitle = bi.ClearTitle
  460. for _, kw := range keys {
  461. kws := strings.Split(kw, "+")
  462. n := 0
  463. otitle := bi.HighlightTitle
  464. for _, kwn := range kws {
  465. ot := strings.Replace(otitle, kwn, "<span class='keys'>"+kwn+"</span>", 1)
  466. if ot != bi.HighlightTitle {
  467. n++
  468. otitle = ot
  469. } else {
  470. break
  471. }
  472. }
  473. if n == len(kws) {
  474. bi.HighlightTitle = otitle
  475. break
  476. }
  477. }
  478. return bi
  479. }
  480. func SortListSplit(list *SortList, f func(v interface{})) {
  481. l := len(*list)
  482. if l == 0 {
  483. return
  484. }
  485. i := Mgo_ListSize
  486. for {
  487. if l > i {
  488. arr := (*list)[i-Mgo_ListSize : i]
  489. f(&arr)
  490. } else if l > i-Mgo_ListSize {
  491. arr := (*list)[i-Mgo_ListSize:]
  492. f(&arr)
  493. break
  494. }
  495. i += Mgo_ListSize
  496. }
  497. }
  498. func CSortListSplit(list *CSortList, f func(v interface{})) {
  499. l := len(*list)
  500. if l == 0 {
  501. return
  502. }
  503. i := Mgo_ListSize
  504. for {
  505. if l > i {
  506. arr := (*list)[i-Mgo_ListSize : i]
  507. f(&arr)
  508. } else if l > i-Mgo_ListSize {
  509. arr := (*list)[i-Mgo_ListSize:]
  510. f(&arr)
  511. break
  512. }
  513. i += Mgo_ListSize
  514. }
  515. }
  516. // 获取企业授权超级订阅/大会员的用户
  517. func LoadEntProductUsers(msl *Mysql, testUserIds []int) (map[string]*UserInfo, map[int]*UserInfo, map[int]*UserInfo, []*UserInfo) {
  518. logger.Info("开始加载企业授权用户。。。")
  519. phoneMap := map[string]*UserInfo{}
  520. userMap := map[int]*UserInfo{}
  521. entMap := map[int]*UserInfo{}
  522. all := []*UserInfo{}
  523. query := `SELECT DISTINCT a.ent_id,IF(instr(a.product_type,'` + Ent_EmpowerMember + `')>0,'` + Ent_EmpowerMember + `','` + Ent_EmpowerVip + `') as product_type,c.phone,b.ent_user_id,d.name as ent_name,d.power_source,d.isNew from jianyu.entniche_wait_empower a
  524. inner join jianyu.entniche_power b on (a.end_time>? and b.status=1 and (a.product_type like '%` + Ent_EmpowerVip + `%' or a.product_type like '%` + Ent_EmpowerMember + `%') and a.id=b.wait_empower_id)
  525. inner join jianyu.entniche_user c on (`
  526. if len(testUserIds) > 0 {
  527. array := []string{}
  528. for _, v := range testUserIds {
  529. array = append(array, fmt.Sprint(v))
  530. }
  531. query += `c.id in (` + strings.Join(array, ",") + `) and `
  532. }
  533. query += `b.ent_user_id=c.id)
  534. inner join jianyu.entniche_info d on (d.id=a.ent_id)`
  535. msl.SelectByBath(200, func(l *[]map[string]interface{}) bool {
  536. for _, v := range *l {
  537. phone, _ := v["phone"].(string)
  538. if phone == "" {
  539. continue
  540. }
  541. u := &UserInfo{
  542. Entniche: &Entniche{
  543. EntId: util.IntAll(v["ent_id"]),
  544. EntName: util.ObjToString(v["ent_name"]),
  545. UserId: util.IntAll(v["ent_user_id"]),
  546. ProductType: util.ObjToString(v["product_type"]),
  547. PowerSource: util.IntAll(v["power_source"]),
  548. IsNew: util.IntAll(v["isNew"]),
  549. },
  550. Phone: phone,
  551. }
  552. if strings.Contains(u.Entniche.ProductType, Ent_EmpowerMember) {
  553. u.MemberStatus = 1
  554. } else if strings.Contains(u.Entniche.ProductType, Ent_EmpowerVip) {
  555. u.VipStatus = 1
  556. } else {
  557. continue
  558. }
  559. phoneMap[phone] = u
  560. userMap[u.Entniche.UserId] = u
  561. all = append(all, u)
  562. entMap[u.Entniche.EntId] = u
  563. logger.Info("加载企业授权用户", u.Entniche.EntName, u.Entniche.EntId, u.Entniche.UserId, u.Entniche.ProductType, u.Phone)
  564. }
  565. return true
  566. }, query, NowFormat(Date_Full_Layout))
  567. logger.Info("企业授权用户加载结束。。。", len(phoneMap), len(userMap), len(entMap), len(all))
  568. return phoneMap, userMap, entMap, all
  569. }
  570. // 加载商机管理用户
  571. func LoadEntnicheUsers(msl *Mysql) map[string]bool {
  572. logger.Info("开始加载新版商机管理用户。。。")
  573. r := map[string]bool{}
  574. msl.SelectByBath(200, func(l *[]map[string]interface{}) bool {
  575. for _, v := range *l {
  576. phone := util.ObjToString(v["phone"])
  577. if phone != "" {
  578. r[phone] = true
  579. logger.Info("加载商机管理用户", phone)
  580. }
  581. }
  582. return true
  583. }, `SELECT b.phone from jianyu.entniche_info a INNER JOIN jianyu.entniche_user b on (a.status=1 and a.power_source is null and b.power=1 and a.id=b.ent_id)`)
  584. logger.Info("商机管理用户加载结束。。。", len(r))
  585. return r
  586. }
  587. func GetWxTplMsg(subSet *SubSet) (string, string) {
  588. keyword := strings.Join(subSet.Keys, " ")
  589. if len([]rune(keyword)) > 100 {
  590. keyword = string([]rune(keyword)[:100]) + "..."
  591. }
  592. area := strings.Join(subSet.Areas, " ")
  593. if len([]rune(area)) > 100 {
  594. area = string([]rune(area)[:100]) + "..."
  595. }
  596. if area == "" {
  597. area = "全国"
  598. }
  599. return keyword, area
  600. }
  601. func GetPhone(u map[string]interface{}) string {
  602. phone := util.ObjToString(u["s_phone"])
  603. if phone == "" {
  604. phone = util.ObjToString(u["s_m_phone"])
  605. }
  606. return phone
  607. }
  608. func GetAllByEntUserId(mgo *MongodbSim, msl *Mysql, entUserId int) *map[string]interface{} {
  609. entUsers := msl.SelectBySql(`select phone from jianyu.entniche_user where id=?`, entUserId)
  610. if entUsers == nil || len(*entUsers) == 0 {
  611. logger.Info("entniche_user表中没有找到该企业用户", entUserId)
  612. return nil
  613. }
  614. phone, _ := (*entUsers)[0]["phone"].(string)
  615. if phone == "" {
  616. return nil
  617. }
  618. return getEntPushSet(mgo, msl, entUserId, phone)
  619. }
  620. func GetAllByEntPositionId(mgo *MongodbSim, msl *Mysql, positionId int) *map[string]interface{} {
  621. position := msl.SelectBySql(`select a.ent_id,b.phone from base_service.base_position a inner join base_service.base_user b on (a.id=? and a.user_id=b.id)`, positionId)
  622. if position == nil || len(*position) == 0 {
  623. logger.Info("无效的职位id", position)
  624. return nil
  625. }
  626. entId := util.Int64All((*position)[0]["ent_id"])
  627. if entId == 0 {
  628. logger.Info("该职位id没有找到对应的企业id", position)
  629. return nil
  630. }
  631. phone, _ := (*position)[0]["phone"].(string)
  632. if phone == "" {
  633. logger.Info("该职位id没有找到对应的手机号", position)
  634. return nil
  635. }
  636. entUsers := msl.SelectBySql(`select id from jianyu.entniche_user where phone=? and ent_id=?`, phone, entId)
  637. if entUsers == nil || len(*entUsers) == 0 {
  638. logger.Info("entniche_user表中没有找到该企业用户", phone, entId)
  639. return nil
  640. }
  641. return getEntPushSet(mgo, msl, util.IntAll((*entUsers)[0]["id"]), phone)
  642. }
  643. func getEntPushSet(mgo *MongodbSim, msl *Mysql, entUserId int, phone string) *map[string]interface{} {
  644. users, ok := mgo.Find(Mgo_User, map[string]interface{}{
  645. "$or": []map[string]interface{}{
  646. map[string]interface{}{
  647. "s_phone": phone,
  648. },
  649. map[string]interface{}{
  650. "s_m_phone": phone,
  651. },
  652. },
  653. }, `{"s_phone":-1}`, map[string]interface{}{
  654. "_id": 1,
  655. "s_m_openid": 1,
  656. "a_m_openid": 1,
  657. "s_phone": 1,
  658. "s_m_phone": 1,
  659. "i_ispush": 1,
  660. "s_jpushid": 1,
  661. "s_opushid": 1,
  662. "s_appponetype": 1,
  663. "base_user_id": 1,
  664. }, false, -1, -1)
  665. if !ok || users == nil || len(*users) == 0 {
  666. logger.Info("user表中没有找到该企业用户", entUserId, phone)
  667. return nil
  668. }
  669. user := map[string]interface{}{}
  670. for _, v := range *users {
  671. if user["_id"] == nil {
  672. user["_id"] = v["_id"]
  673. user["base_user_id"] = v["base_user_id"]
  674. }
  675. if user["s_phone"] == nil && util.ObjToString(v["s_phone"]) != "" {
  676. user["s_phone"] = v["s_phone"]
  677. }
  678. if user["s_m_phone"] == nil && util.ObjToString(v["s_m_phone"]) != "" {
  679. user["s_m_phone"] = v["s_m_phone"]
  680. }
  681. if user["a_m_openid"] == nil && util.ObjToString(v["a_m_openid"]) != "" {
  682. user["a_m_openid"] = v["a_m_openid"]
  683. }
  684. s_m_openid := util.ObjToString(v["s_m_openid"])
  685. i_ispush := util.IntAll(v["i_ispush"])
  686. s_jpushid := util.ObjToString(v["s_jpushid"])
  687. s_opushid := util.ObjToString(v["s_opushid"])
  688. s_appponetype := util.ObjToString(v["s_appponetype"])
  689. if user["s_m_openid"] == nil && user["i_ispush"] == nil && s_m_openid != "" && i_ispush == 1 {
  690. user["s_m_openid"] = s_m_openid
  691. user["i_ispush"] = i_ispush
  692. }
  693. if user["s_jpushid"] == nil && user["s_opushid"] == nil && user["s_appponetype"] == nil && s_appponetype != "" && (s_jpushid != "" || s_opushid != "") {
  694. user["s_jpushid"] = s_jpushid
  695. user["s_opushid"] = s_opushid
  696. user["s_appponetype"] = s_appponetype
  697. }
  698. }
  699. entniche_user, ok := mgo.FindOneByField(Mgo_Ent_User, map[string]interface{}{
  700. "i_userid": entUserId,
  701. }, `{"_id":0,"i_member_status":1,"i_vip_status":1,"o_pushset":1}`)
  702. if ok && entniche_user != nil && len(*entniche_user) > 0 {
  703. for k, v := range *entniche_user {
  704. user[k] = v
  705. }
  706. }
  707. entniche_rule, ok := mgo.Find("entniche_rule", map[string]interface{}{
  708. "i_userid": entUserId,
  709. }, nil, `{"_id":0,"o_entniche":1,"i_type":1}`, false, -1, -1)
  710. if ok && entniche_rule != nil {
  711. for _, v := range *entniche_rule {
  712. i_type := util.IntAll(v["i_type"])
  713. if i_type == 0 {
  714. user["o_entniche"] = v["o_entniche"]
  715. } else if i_type == 1 {
  716. user["o_vipjy"] = v["o_entniche"]
  717. user["o_member_jy"] = v["o_entniche"]
  718. } else if i_type == 2 {
  719. user["o_jy"] = v["o_entniche"]
  720. }
  721. }
  722. }
  723. return &user
  724. }
  725. func GetEntUserPushset(mgo *MongodbSim, entUserId int) map[string]interface{} {
  726. temp, ok := mgo.FindOneByField(Mgo_Ent_User, map[string]interface{}{
  727. "i_userid": entUserId,
  728. }, `{"o_pushset":1}`)
  729. if ok && temp != nil && len(*temp) > 0 {
  730. o_pushset, _ := (*temp)["o_pushset"].(map[string]interface{})
  731. return o_pushset
  732. }
  733. return nil
  734. }
  735. func GetEntUserSubset(mgo *MongodbSim, entUserId, tp int) map[string]interface{} {
  736. temp, ok := mgo.FindOneByField("entniche_rule", map[string]interface{}{
  737. "i_userid": entUserId,
  738. "i_type": tp,
  739. }, `{"o_entniche":1}`)
  740. if ok && temp != nil && len(*temp) > 0 {
  741. o_msgset, _ := (*temp)["o_entniche"].(map[string]interface{})
  742. return o_msgset
  743. }
  744. return nil
  745. }
  746. // 格式化小时
  747. func HourFormat(hour int) string {
  748. if hour < 10 {
  749. return fmt.Sprintf("0%d:00", hour)
  750. } else {
  751. return fmt.Sprintf("%d:00", hour)
  752. }
  753. }
  754. // 数组中的小时是否结束
  755. func TimesIsOver(times []string, hour int) (bool, time.Time, time.Time) {
  756. now := time.Now()
  757. if len(times) == 0 {
  758. return false, now, now
  759. }
  760. sort.Strings(times)
  761. lastHour := util.IntAll(strings.Split(times[len(times)-1], ":")[0])
  762. //跨天
  763. if lastHour == 23 && hour == 0 {
  764. start := time.Date(now.Year(), now.Month(), now.Day()-1, 0, 0, 0, 0, time.Local)
  765. end := time.Date(now.Year(), now.Month(), now.Day()-1, 23, 59, 59, 0, time.Local)
  766. return true, start, end
  767. } else {
  768. start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
  769. return hour-1 == lastHour, start, now
  770. }
  771. }
  772. // 监听超时
  773. func MonitorTimeOut(pool chan bool, timeout time.Duration, warn string, f func()) bool {
  774. select {
  775. case <-time.After(timeout):
  776. go func() {
  777. f()
  778. if warn != "" {
  779. if _, err := http.Get(warn); err != nil {
  780. logger.Error("发送告警邮件错误", err)
  781. }
  782. }
  783. }()
  784. return false
  785. case pool <- true:
  786. }
  787. return true
  788. }
  789. // 根据职位id获取用户信息
  790. func GetUserInfoByPosition(msl *Mysql, mgo *MongodbSim, id int64) *UserInfo {
  791. list := msl.SelectBySql(`select user_id from base_service.base_position where id=?`, id)
  792. if list == nil || len(*list) == 0 {
  793. return nil
  794. }
  795. data, ok := mgo.FindOneByField("user", map[string]interface{}{
  796. "base_user_id": util.Int64All((*list)[0]["user_id"]),
  797. }, `{"_id":1}`)
  798. if !ok || data == nil || len(*data) == 0 {
  799. return nil
  800. }
  801. return &UserInfo{
  802. Id: BsonIdToSId((*data)["_id"]),
  803. }
  804. }
  805. // 资源中台权益
  806. var rcpLock = &sync.Mutex{}
  807. func ResourceCenterPowers(msl *Mysql, positionId int64) map[string]bool {
  808. rcpLock.Lock()
  809. if rcDb.Mysql_BaseService == nil {
  810. rcDb.Mysql_BaseService = &Mysql{
  811. Address: msl.Address,
  812. UserName: msl.UserName,
  813. PassWord: msl.PassWord,
  814. DBName: "base_service",
  815. MaxOpenConns: msl.MaxOpenConns,
  816. MaxIdleConns: msl.MaxIdleConns,
  817. }
  818. rcDb.Mysql_BaseService.Init()
  819. }
  820. rcpLock.Unlock()
  821. powers := map[string]bool{}
  822. if identity := IdentityByPositionId(msl, positionId); identity != nil {
  823. list, _ := rcService.HasPowers("10000", identity.AccountId, identity.EntAccountId, identity.EntId, identity.EntUserId)
  824. for _, v := range list {
  825. powers[v] = true
  826. }
  827. }
  828. return powers
  829. }
  830. func MergeDiffIndustry(wuye, other *[]map[string]interface{}) *[]map[string]interface{} {
  831. m := map[string]map[string]interface{}{}
  832. for _, v := range *wuye {
  833. _id := BsonIdToSId(v["_id"])
  834. tag_topinformation, _ := v["tag_topinformation"].([]interface{})
  835. for _, vv := range tag_topinformation {
  836. if vv != "情报_物业" {
  837. continue
  838. }
  839. m[_id] = v
  840. }
  841. }
  842. for _, v := range *other {
  843. _id := BsonIdToSId(v["_id"])
  844. tag_topinformation, _ := v["tag_topinformation"].([]interface{})
  845. if len(tag_topinformation) == 1 && tag_topinformation[0] == "情报_物业" {
  846. continue
  847. }
  848. m[_id] = v
  849. }
  850. datas := []map[string]interface{}{}
  851. for _, v := range m {
  852. datas = append(datas, v)
  853. }
  854. return &datas
  855. }
  856. // 获取无消息提醒微信模板消息的可用数量
  857. func WxNoMsgTmplUsableNum(mgo *MongodbSim, wxNodeNum, dayNum, count, retain int64) int64 {
  858. if count < 0 {
  859. return -1
  860. }
  861. ymds := []string{}
  862. now := time.Now()
  863. for i := 0; i < int(dayNum); i++ {
  864. now = now.AddDate(0, 0, -1)
  865. ymds = append(ymds, FormatDate(&now, Date_Short_Layout))
  866. }
  867. list, ok := mgo.Find("wxtmplsend_tj", map[string]interface{}{"type": map[string]interface{}{"$in": []string{"all", "free_nomsg"}}, "ymd": map[string]interface{}{"$in": ymds}}, `{"ymd":-1}`, `{"count":1,"node":1,"ymd":1,"type":1}`, false, -1, -1)
  868. if !ok || list == nil || len(*list) == 0 {
  869. logger.Error("wxtmplsend_tj没有找到记录", ymds)
  870. return 0
  871. }
  872. all := map[string]map[string]int64{}
  873. ymdCount := map[string]int64{}
  874. ymdNoMsgCount := map[string]int64{}
  875. for _, v := range *list {
  876. ymd, _ := v["ymd"].(string)
  877. if all[ymd] == nil {
  878. all[ymd] = map[string]int64{}
  879. }
  880. tp := ObjToString(v["type"])
  881. all[ymd][fmt.Sprintf("%s %s", tp, ObjToString(v["node"]))]++
  882. if tp == "all" {
  883. ymdCount[ymd] += Int64All(v["count"])
  884. } else {
  885. ymdNoMsgCount[ymd] += Int64All(v["count"])
  886. }
  887. }
  888. var index, maxNum, maxNoMsgNum int64
  889. var hitYmd string
  890. L:
  891. for _, v := range ymds {
  892. if all[v] == nil || int64(len(all[v])) != wxNodeNum+1 {
  893. continue
  894. }
  895. for _, vv := range all[v] {
  896. if vv != 1 {
  897. continue L
  898. }
  899. }
  900. index++
  901. if maxNum < ymdCount[v] {
  902. hitYmd = v
  903. maxNum = ymdCount[v]
  904. maxNoMsgNum = ymdNoMsgCount[v]
  905. }
  906. }
  907. if index < dayNum/2 {
  908. logger.Error("计算以往最大推送量异常", index, dayNum/2)
  909. return 0
  910. }
  911. surplus := count - maxNum - retain + maxNoMsgNum
  912. if surplus < 0 {
  913. return 0
  914. }
  915. logger.Info("微信模板消息最大量", count, ",过去", dayNum, "天", hitYmd, "的推送量最大", maxNum, ",无消息提醒的推送量", maxNoMsgNum, ",保留", retain, ",剩余可用", surplus)
  916. return surplus
  917. }