main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/garyburd/redigo/redis"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/bson/primitive"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. "go.mongodb.org/mongo-driver/mongo/options"
  11. "log"
  12. mu "mfw/util"
  13. "net"
  14. elastic "qfw/common/src/qfw/util/elastic"
  15. "qfw/util"
  16. "sort"
  17. "strings"
  18. "time"
  19. )
  20. var
  21. (
  22. Config = make(map[string]string)
  23. Fields []string
  24. SourceClient, FClient *mongo.Client
  25. RedisPool redis.Pool
  26. Addrs = make(map[string]interface{}, 0) //省市县
  27. udpclient mu.UdpClient //udp对象
  28. ElasticClientIndex, ElasticClientType string
  29. )
  30. /**
  31. 新增
  32. 初始化
  33. */
  34. func init() {
  35. log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
  36. util.ReadConfig(&Config)
  37. log.Println(Config)
  38. Fields = []string{"_id", "contact", "partners", "business_scope", "company_address", "capital",
  39. "establish_date", "legal_person", "company_type", "district", "city", "province", "area_code", "credit_no",
  40. "company_name", "history_name", "topscopeclass", "wechat_accounts", "alias","website","report_websites"}
  41. var err error
  42. //mongo init
  43. SourceClient, err = mongo.NewClient(options.Client().ApplyURI("mongodb://" + Config["mgoinit"]).SetMaxPoolSize(20))
  44. if err != nil {
  45. log.Fatalln(err)
  46. }
  47. c1 := context.Background()
  48. err = SourceClient.Connect(c1)
  49. //defer SourceClient.Disconnect(c1)
  50. if err != nil {
  51. log.Fatalln(err)
  52. }
  53. FClient, err = mongo.NewClient(options.Client().ApplyURI("mongodb://" + Config["mgourl"]).SetMaxPoolSize(20))
  54. if err != nil {
  55. log.Fatalln(err)
  56. }
  57. cc := context.Background()
  58. err = FClient.Connect(cc)
  59. //defer FClient.Disconnect(cc)
  60. if err != nil {
  61. log.Fatalln(err)
  62. }
  63. //加载省市县代码
  64. cursor2, err := FClient.Database(Config["mgodb_extract_kf"]).Collection("address").Find(cc, bson.M{},
  65. options.Find().SetProjection(bson.M{"province": 1, "code": 1, "city": 1, "district": 1}))
  66. defer cursor2.Close(cc)
  67. defer FClient.Connect(cc)
  68. if err != nil {
  69. log.Fatalln(err)
  70. }
  71. for cursor2.Next(cc) {
  72. tmp := make(map[string]interface{})
  73. if err := cursor2.Decode(&tmp); err != nil {
  74. log.Println(err)
  75. continue
  76. } else {
  77. code := tmp["code"]
  78. if code != nil && strings.TrimSpace(code.(string)) != "" {
  79. Addrs[fmt.Sprint(code)] = tmp
  80. }
  81. }
  82. }
  83. log.Println(len(Addrs))
  84. //es.NewClient(es.SetURL(addrs...), es.SetMaxRetries(2), es.SetSniff(false))
  85. //es init
  86. elastic.InitElasticSize(Config["elasticsearch"],10)
  87. //esConn := elastic.GetEsConn()
  88. //defer elastic.DestoryEsConn(esConn)
  89. //log.Println(esConn.Index().Index(Config["elasticsearch_index"]).Type(Config["elasticsearch_type"]).Id("123").BodyJson(map[string]interface{}{"testname":"六盘水市钟山开发区亿农科贸有限公司"}).Refresh(true).Do())
  90. //log.Println(esConn.Delete().Index(Config["elasticsearch_index"]).Type(Config["elasticsearch_type"]).Id("123").Refresh(true).Do())
  91. //if ESclient, err = elastic.NewClient(elastic.SetURL(Config["elasticsearch"]), elastic.SetHealthcheckTimeout(time.Minute)); err != nil {
  92. // log.Println(Config["elasticsearch"])
  93. // log.Fatalln("ElasticClient err:", err)
  94. //} else {
  95. // ElasticClientIndex = Config["elasticsearch_index"]
  96. // ElasticClientType = Config["elasticsearch_type"]
  97. //}
  98. //redis
  99. RedisPool = redis.Pool{
  100. MaxIdle: 10,
  101. IdleTimeout: 240 * time.Second,
  102. Dial: func() (redis.Conn, error) {
  103. conn, e := redis.Dial("tcp", Config["redis"])
  104. if e != nil {
  105. return conn, e
  106. }
  107. _, err = conn.Do("SELECT", "1")
  108. if err != nil {
  109. return nil, err
  110. }
  111. return conn, nil
  112. },}
  113. c := RedisPool.Get()
  114. if _, err := c.Do("PING"); err != nil {
  115. log.Fatalln(err)
  116. }
  117. defer c.Close()
  118. }
  119. func main() {
  120. //udp
  121. updport := Config["udpport"]
  122. udpclient = mu.UdpClient{Local: updport, BufSize: 1024}
  123. udpclient.Listen(processUdpMsg)
  124. log.Println("Udp服务监听", updport)
  125. go TimedTask() //定时任务
  126. c := make(chan int, 1)
  127. <-c
  128. }
  129. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  130. log.Println(act, string(data), ra)
  131. switch act {
  132. case mu.OP_TYPE_DATA: //上个节点的数据
  133. //从表中开始处理生成企业数据
  134. tmp := new(map[string]interface{})
  135. err := json.Unmarshal(data, &tmp)
  136. if err != nil {
  137. log.Println("err:", err)
  138. udpclient.WriteUdp([]byte("err:"+err.Error()), mu.OP_NOOP, ra)
  139. return
  140. } else if tmp != nil {
  141. udpclient.WriteUdp([]byte("ok,run"), mu.OP_NOOP, ra)
  142. go task(tmp)
  143. }
  144. case mu.OP_NOOP: //下个节点回应
  145. log.Println("发送成功", string(data))
  146. }
  147. }
  148. func task(mapinfo *map[string]interface{}) {
  149. defer util.Catch()
  150. gtid, lteid := util.ObjToString((*mapinfo)["gtid"]), util.ObjToString((*mapinfo)["lteid"])
  151. if gtid == "" || lteid == "" {
  152. log.Println(gtid, lteid, "参数错误")
  153. return
  154. }
  155. GId, err := primitive.ObjectIDFromHex(gtid)
  156. LtId, err2 := primitive.ObjectIDFromHex(lteid)
  157. if err != nil || err2 != nil {
  158. log.Println(gtid, lteid, "转换_id错误")
  159. return
  160. }
  161. //udp的id区间查询bidding 中标人 中标联系人 中标联系电话
  162. // topscopeclass项目类型-industry行业类型&&topscopeclass联系人项目类型
  163. // (area地区-province省份 city城市-city城市 district区县-district区县)
  164. // winneraddr-company_address企业地址
  165. cursor, err := SourceClient.Database(Config["mgodb_bidding"]).Collection("bidding").Find(context.TODO(), bson.M{
  166. "_id": bson.M{
  167. "$gte": GId,
  168. "$lte": LtId,
  169. },
  170. }, options.Find().SetProjection(bson.M{"winner": 1, "winnertel": 1, "winnerperson": 1,
  171. "topscopeclass": 1, "winneraddr": 1}))
  172. if err != nil {
  173. log.Println(err)
  174. return
  175. }
  176. for cursor.Next(context.TODO()) {
  177. tmp := map[string]interface{}{}
  178. if err := cursor.Decode(&tmp); err == nil {
  179. if tmp["winner"] == nil || tmp["winner"] == "" {
  180. continue
  181. }
  182. //redis查询是否存在
  183. rdb := RedisPool.Get()
  184. defer rdb.Close()
  185. if reply, err := redis.String(rdb.Do("GET", tmp["winner"])); err != nil {
  186. //redis不存在存到临时表,定时任务处理
  187. FClient.Database(Config["mgodb_extract_kf"]).Collection("tmp_winner_qyk").InsertOne(context.TODO(), tmp)
  188. //log.Println(tmp, err)
  189. continue
  190. } else {
  191. //redis存在
  192. //log.Println(reply)
  193. //reply = "5e0316b998a9abaf6535df3d"
  194. id, err := primitive.ObjectIDFromHex(reply)
  195. if err != nil {
  196. log.Println("get redis id err:", err, tmp)
  197. continue
  198. }
  199. //拿到合并后的qyk
  200. oldTmp := make(map[string]interface{})
  201. err = FClient.Database(Config["mgodb_extract_kf"]).Collection(Config["mgo_qyk_c"]).
  202. FindOne(context.TODO(), bson.M{"_id": id}).Decode(&oldTmp)
  203. if err != nil {
  204. log.Println("qyk id err:", err, id)
  205. continue
  206. }
  207. //比较合并
  208. //行业类型
  209. tmpTopscopeclass := []string{}
  210. tmpTopscopeclassMap := make(map[string]bool)
  211. log.Println(tmp["_id"])
  212. if oldTmp["industry"] == nil {
  213. //log.Println(reflect.ValueOf(tmp["topscopeclass"]))
  214. if v, ok := tmp["topscopeclass"].(primitive.A); ok {
  215. for _, vv := range v {
  216. if vvv, ok := vv.(string); ok && len(vvv) > 1 {
  217. tmpTopscopeclassMap[vvv[:len(vvv)-1]] = true
  218. }
  219. }
  220. for k := range tmpTopscopeclassMap {
  221. tmpTopscopeclass = append(tmpTopscopeclass, k)
  222. }
  223. }
  224. } else {
  225. if v, ok := oldTmp["industry"].(primitive.A); ok {
  226. for _, vv := range v {
  227. if vvv, ok := vv.(string); ok {
  228. tmpTopscopeclassMap[vvv] = true
  229. }
  230. }
  231. }
  232. if v, ok := tmp["topscopeclass"].(primitive.A); ok {
  233. for _, vv := range v {
  234. if vvv, ok := vv.(string); ok && len(vvv) > 1 {
  235. tmpTopscopeclassMap[vvv[:len(vvv)-1]] = true
  236. }
  237. }
  238. for k := range tmpTopscopeclassMap {
  239. tmpTopscopeclass = append(tmpTopscopeclass, k)
  240. }
  241. }
  242. }
  243. sort.Strings(tmpTopscopeclass)
  244. oldTmp["industry"] = tmpTopscopeclass
  245. esId := oldTmp["_id"].(primitive.ObjectID).Hex()
  246. //联系方式合并
  247. if tmp["winnerperson"] == nil || tmp["winnerperson"] == "" {
  248. oldTmp["updatatime"] =time.Now().Unix()
  249. //mongo更新
  250. FClient.Database(Config["mgodb_extract_kf"]).Collection(Config["mgo_qyk_c"]).
  251. UpdateOne(context.TODO(), bson.M{"_id": oldTmp["_id"]}, bson.M{"$set": oldTmp})
  252. //es更新
  253. delete(oldTmp, "_id")
  254. esConn := elastic.GetEsConn()
  255. defer elastic.DestoryEsConn(esConn)
  256. esConn.Update().Index(Config["elasticsearch_index"]).Type(Config["elasticsearch_type"]).Id(esId).Doc(oldTmp).Refresh(true).Do()
  257. //log.Println( err2,err3)
  258. continue
  259. }
  260. var tmpperson, winnertel string
  261. tmpperson = tmp["winnerperson"].(string)
  262. if tmp["winnertel"] == nil {
  263. winnertel = ""
  264. }
  265. contactMaps := make([]interface{}, 0)
  266. if oldTmp["contact"] == nil {
  267. tmpContact := make(map[string]interface{})
  268. tmpContact["contact_person"] = tmpperson
  269. tmpContact["contact_type"] = "项目联系人"
  270. tmpContact["phone"] = winnertel
  271. tmpContact["topscopeclass"] = strings.Join(tmpTopscopeclass, ";")
  272. tmpContact["updatetime"] = time.Now().Unix()
  273. contactMaps = append(contactMaps, tmpContact)
  274. } else {
  275. //对比前四项,相等丢弃
  276. if v, ok := oldTmp["contact"].(primitive.A); ok {
  277. var isNotUpdate bool
  278. for _, vv := range v {
  279. if vvv, ok := vv.(map[string]interface{}); ok {
  280. if vvv["contact_person"] == tmpperson && vvv["contact_type"] == "项目联系人" &&
  281. vvv["phone"] == winnertel && vvv["topscopeclass"] == strings.Join(tmpTopscopeclass, ";") {
  282. isNotUpdate = true
  283. vvv["updatetime"] = time.Now().Unix()
  284. }
  285. contactMaps = append(contactMaps, vvv)
  286. }
  287. }
  288. if !isNotUpdate {
  289. vvv := make(map[string]interface{})
  290. vvv["contact_person"] = tmp["winnerperson"]
  291. vvv["contact_type"] = "项目联系人"
  292. vvv["phone"] = winnertel
  293. vvv["topscopeclass"] = strings.Join(tmpTopscopeclass, ";")
  294. vvv["updatetime"] = time.Now().Unix()
  295. contactMaps = append(contactMaps, vvv)
  296. }
  297. }
  298. }
  299. oldTmp["contact"] = contactMaps
  300. //mongo更新
  301. oldTmp["updatatime"] =time.Now().Unix()
  302. FClient.Database(Config["mgodb_extract_kf"]).Collection(Config["mgo_qyk_c"]).
  303. UpdateOne(context.TODO(), bson.M{"_id": oldTmp["_id"]}, bson.M{"$set": oldTmp})
  304. //es更新
  305. delete(oldTmp, "_id")
  306. esConn := elastic.GetEsConn()
  307. defer elastic.DestoryEsConn(esConn)
  308. esConn.Update().Index(Config["elasticsearch_index"]).Type(Config["elasticsearch_type"]).Id(esId).Doc(oldTmp).Refresh(true).Do()
  309. //log.Println( err2,err3)
  310. }
  311. } else {
  312. log.Println(tmp)
  313. continue
  314. }
  315. }
  316. defer cursor.Close(context.TODO())
  317. //tmps := make([]interface{}, 0)
  318. //num, snum := 0, 0
  319. //for k := range keys {
  320. // //if num == 6 {
  321. // // return
  322. // //}
  323. // tmp := make(map[string]interface{})
  324. // err := Client.Database("enterprise").Collection("qyxy").FindOne(context.TODO(), bson.M{"company_name": k}).Decode(&tmp)
  325. // if err != nil {
  326. // //log.Println(k, err)
  327. // continue
  328. // }
  329. // if tmp["credit_no"] != nil {
  330. // if credit_no, ok := tmp["credit_no"].(string); ok && strings.TrimSpace(credit_no) != "" &&
  331. // len(strings.TrimSpace(credit_no)) > 8 {
  332. // dataNo := strings.TrimSpace(credit_no)[2:8]
  333. // if Addrs[dataNo] != nil {
  334. // if v, ok := Addrs[dataNo].(map[string]interface{}); ok {
  335. // if tmp["province"] == nil || tmp["province"] == "" {
  336. // tmp["province"] = v["province"]
  337. // }
  338. // tmp["city"] = v["city"]
  339. // tmp["district"] = v["district"]
  340. //
  341. // }
  342. // }
  343. // }
  344. // }
  345. // contacts := make([]map[string]interface{}, 0)
  346. // contact := make(map[string]interface{}, 0)
  347. // if tmp["legal_person"] != nil {
  348. // contact["contact_person"] = tmp["legal_person"] //联系人
  349. // } else {
  350. // contact["contact_person"] = "" //联系人
  351. // }
  352. // contact["contact_type"] = "法定代表人" //法定代表人
  353. // //log.Println(1)
  354. // if tmp["annual_reports"] != nil {
  355. // bytes, err := json.Marshal(tmp["annual_reports"])
  356. // if err != nil {
  357. // log.Println("annual_reports err:", err)
  358. // }
  359. // //log.Println(2, string(bytes))
  360. // phonetmp := make([]map[string]interface{}, 0)
  361. // err = json.Unmarshal(bytes, &phonetmp)
  362. // if err != nil {
  363. // log.Println("Unmarshal err:", err)
  364. // }
  365. // //log.Println(44, err)
  366. // for _, vv := range phonetmp {
  367. // if vv["company_phone"] != nil {
  368. // if vv["company_phone"] == "" {
  369. // continue
  370. // } else {
  371. // contact["phone"] = vv["company_phone"] //联系电话
  372. // break
  373. // }
  374. // } else {
  375. // contact["phone"] = "" //联系电话
  376. // }
  377. //
  378. // }
  379. // }
  380. // //log.Println(k, contact["phone"], tmp["_id"])
  381. // //time.Sleep(10 * time.Second)
  382. // if contact["phone"] == nil {
  383. // contact["phone"] = "" //联系电话
  384. // }
  385. // contact["topscopeclass"] = "企业公示" //项目类型
  386. // contact["updatetime"] = time.Now().Unix() //更新时间
  387. // contacts = append(contacts, contact)
  388. // tmp["contact"] = contacts
  389. //
  390. // savetmp := make(map[string]interface{}, 0)
  391. // //字段处理
  392. // for _, sk := range Fields {
  393. // if sk == "establish_date" { //成立日期
  394. // if tmp[sk] != nil {
  395. // savetmp[sk] = tmp[sk].(primitive.DateTime).Time().UTC().Unix()
  396. // continue
  397. // }
  398. // } else if sk == "capital" { //注册资本
  399. // //log.Println(sk, tmp[sk])
  400. // savetmp[sk] = ObjToMoney([]interface{}{tmp[sk], ""})[0]
  401. // continue
  402. // } else if sk == "partners" { //股东及出资信息
  403. // //log.Println(sk, tmp[sk], )
  404. // //fmt.Println(reflect.TypeOf(tmp[sk]))
  405. // if tmp[sk] != nil {
  406. // if ppms, ok := tmp[sk].(primitive.A); ok {
  407. // for i, _ := range ppms {
  408. // if ppms[i].(map[string]interface{})["stock_type"] != nil {
  409. // ppms[i].(map[string]interface{})["stock_type"] = "企业公示"
  410. // }
  411. // delete(ppms[i].(map[string]interface{}), "identify_type")
  412. // }
  413. // savetmp[sk] = ppms
  414. // continue
  415. // }
  416. // }
  417. // } else if sk == "_id" { //_id备份企业库
  418. // savetmp["tmp"+sk] = tmp[sk]
  419. // continue
  420. // }
  421. // if tmp[sk] == nil && sk != "history_name" && sk != "establish_date" && sk != "capital" && sk != "partners" && sk != "contact" && sk != "wechat_accounts" {
  422. // savetmp[sk] = ""
  423. // } else {
  424. // if sk == "wechat_accounts" { //微信公众号
  425. // if savetmp[sk] == nil {
  426. // //TODO 微信公众号取值未确认
  427. // savetmp[sk] = []string{}
  428. // }
  429. // continue
  430. // } else if sk == "website" { //网址
  431. // //TODO 网址取值未确认
  432. // continue
  433. // }
  434. // savetmp[sk] = tmp[sk]
  435. // }
  436. // }
  437. // savetmp["alias"] = "" //别名
  438. // tmps = append(tmps, savetmp)
  439. // num++
  440. // snum++
  441. // if snum >= 300 {
  442. // _, err := Client.Database("extract_v3").Collection("enterprise_qyxy").InsertMany(context.TODO(), tmps)
  443. // if err != nil {
  444. // log.Println("save:", err)
  445. // continue
  446. // } else {
  447. // log.Println(num)
  448. // tmps = []interface{}{}
  449. // snum = 0
  450. // }
  451. // }
  452. //}
  453. //if len(tmps) > 0 {
  454. // result, err := Client.Database("extract_v3").Collection("enterprise_qyxy").InsertMany(context.TODO(), tmps)
  455. // if err != nil {
  456. // log.Println("save over:", err)
  457. // } else {
  458. // log.Println("last save num:", len(result.InsertedIDs))
  459. // }
  460. //}
  461. }