participateStatistics.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. package service
  2. import (
  3. "app.yhyue.com/moapp/jybase/common"
  4. "app.yhyue.com/moapp/jybase/date"
  5. "app.yhyue.com/moapp/jybase/encrypt"
  6. "app.yhyue.com/moapp/jybase/redis"
  7. "encoding/json"
  8. "fmt"
  9. "jyBXCore/rpc/bxcore"
  10. IC "jyBXCore/rpc/init"
  11. "jyBXCore/rpc/model/es"
  12. "log"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. const (
  18. //角色
  19. Role_admin_system = 1 //系统管理员
  20. Role_admin_department = 2 //部门管理员
  21. )
  22. type ParticipateStatistics struct {
  23. PositionId int64
  24. EntId int64
  25. DeptId int64
  26. EntUserId int64
  27. }
  28. func (in *ParticipateStatistics) PushStatistics(entUserIdArr []string, startTime, endTime int64, source []int64) (result []*bxcore.PushStatisticsData) {
  29. //判断是企业、部门还是个人
  30. isAdmin, personArrStr, users := in.PersonHandle(entUserIdArr)
  31. //时间处理
  32. query := QueryHandle(isAdmin, startTime, endTime, personArrStr, source, 0)
  33. //推送数据查询
  34. dataList := IC.BaseMysql.SelectBySql(fmt.Sprintf("select * from participate_push_statistics where %s order by ymd", strings.Join(query, " and ")))
  35. if users != nil && len(*users) > 0 {
  36. result = PushHandle(dataList, users, isAdmin)
  37. }
  38. return
  39. }
  40. func (in *ParticipateStatistics) ProjectStatistics(entUserIdArr []string, startTime, endTime, bidWay int64) (result []*bxcore.ProjectStatisticsData) {
  41. //判断是企业、部门还是个人
  42. isAdmin, personArrStr, users := in.PersonHandle(entUserIdArr)
  43. query := QueryHandle(isAdmin, startTime, endTime, personArrStr, []int64{}, bidWay)
  44. //订阅推送数处理
  45. //推送数据查询
  46. // 调整为时间倒序 处理投标阶段的时候 只取最新的一条的数据
  47. dataList := IC.BaseMysql.SelectBySql(fmt.Sprintf("select * from participate_project_statistics where %s order by ymd desc ", strings.Join(query, "and ")))
  48. if users != nil && len(*users) > 0 {
  49. result = ProjectHandle(dataList, users, isAdmin)
  50. }
  51. return
  52. }
  53. var (
  54. SelectItemMap = map[int]string{
  55. 1: "个人订阅",
  56. 2: "企业自动分发",
  57. 3: "企业手动分发",
  58. }
  59. SourceMap = map[string]string{
  60. "1": "个人订阅",
  61. "2": "企业自动分发",
  62. "3": "企业手动分发",
  63. }
  64. )
  65. // GetSourceItem 获取标讯项目来源筛选项
  66. func (in *ParticipateStatistics) GetSourceItem(entId, positionId int) (result []*bxcore.SourceItem) {
  67. redisKey := "sourceItem%s_%s"
  68. query := "select distinct `source` from participate_push_statistics where "
  69. // 个人用户
  70. if entId == 0 {
  71. // 查职位id
  72. query += fmt.Sprintf(" position_id =%d", positionId)
  73. redisKey = fmt.Sprintf(redisKey, "personal", positionId)
  74. } else {
  75. // 企业用户 用企业id查
  76. query += fmt.Sprintf(" end =%d", entId)
  77. redisKey = fmt.Sprintf(redisKey, "ent", entId)
  78. }
  79. if data, err := redis.GetBytes("other", redisKey); err == nil && data != nil {
  80. err := json.Unmarshal(*data, &result)
  81. if err == nil {
  82. return result
  83. } else {
  84. log.Println("序列化失败", redisKey, err)
  85. }
  86. }
  87. //
  88. rs := IC.BaseMysql.SelectBySql(query)
  89. if rs == nil || len(*rs) == 0 {
  90. return
  91. }
  92. for i := 0; i < len(*rs); i++ {
  93. value := common.ObjToString((*rs)[i]["source"])
  94. if value == "" {
  95. continue
  96. }
  97. splitSource := strings.Split(value, ",")
  98. for j := 0; j < len(splitSource); j++ {
  99. sourceValue, err := strconv.Atoi(splitSource[j])
  100. if err != nil {
  101. log.Println("类型转换错误:", err, splitSource[j])
  102. continue
  103. }
  104. if name, ok := SelectItemMap[sourceValue]; ok {
  105. result = append(result, &bxcore.SourceItem{
  106. Name: name,
  107. Value: int64(sourceValue),
  108. })
  109. }
  110. }
  111. }
  112. if len(result) > 0 {
  113. // 存缓存
  114. rsByte, _ := json.Marshal(result)
  115. redis.PutBytes("other", redisKey, &rsByte, 60*60*2)
  116. }
  117. return
  118. }
  119. func (in *ParticipateStatistics) PersonHandle(entUserIdArr []string) (isAdmin bool, idStr string, users *[]map[string]interface{}) {
  120. userEnt := EntInfo(common.IntAll(in.EntId), common.IntAll(in.EntUserId))
  121. if len(entUserIdArr) > 0 {
  122. //查询所选人的部门以及人员信息
  123. users = GetUser(entUserIdArr)
  124. //返回所选人的信息
  125. isAdmin = true
  126. idStr = strings.Join(entUserIdArr, ",")
  127. } else {
  128. if userEnt.Role_admin_department || userEnt.Role_admin_system { //
  129. // 部门管理员 获取所有部门和子部门员工
  130. users = GetDisUsers(common.IntAll(in.EntId), userEnt.Dept.Id)
  131. var staffs []string
  132. if users != nil && len(*users) > 0 {
  133. for _, v := range *users {
  134. staffs = append(staffs, common.InterfaceToStr(v["id"]))
  135. }
  136. }
  137. isAdmin = true
  138. idStr = strings.Join(staffs, ",")
  139. } else {
  140. if userEnt.Dept.Id != 0 {
  141. entUserIdArr = append(entUserIdArr, common.InterfaceToStr(in.EntUserId))
  142. users = GetUser(entUserIdArr)
  143. //返回所选人的信息
  144. isAdmin = true
  145. idStr = strings.Join(entUserIdArr, ",")
  146. } else {
  147. isAdmin = false
  148. idStr = common.InterfaceToStr(in.PositionId)
  149. users = &[]map[string]interface{}{
  150. map[string]interface{}{
  151. "id": in.PositionId,
  152. "name": "个人",
  153. },
  154. }
  155. }
  156. }
  157. }
  158. return
  159. }
  160. type PushData struct {
  161. PersonName string
  162. entUserId string
  163. DepartmentName string
  164. PushNumb map[string]interface{}
  165. ParticipateNumb map[string]interface{}
  166. BidNumb map[string]interface{}
  167. WinNumb map[string]interface{}
  168. BrowseNumb map[string]interface{}
  169. }
  170. type ProjectData struct {
  171. PersonName string
  172. DepartmentName string
  173. entUserId string
  174. BidNumb map[string]interface{} //投标数量
  175. DirectBidNumb map[string]interface{} //直接投标数
  176. ChannelBidNumb map[string]interface{} //渠道投标数
  177. WinNumb map[string]interface{}
  178. DirectWinNumb map[string]interface{} //直接中标数
  179. ChannelWinNumb map[string]interface{} //渠道中标数
  180. NotBidNumber map[string]interface{} //未中标数量
  181. EndNumb map[string]interface{} //终止数量
  182. participateProjectNumb map[string]interface{} // 参标数量
  183. Stage map[string]map[string]interface{}
  184. }
  185. func PushHandle(data *[]map[string]interface{}, users *[]map[string]interface{}, isAdmin bool) []*bxcore.PushStatisticsData {
  186. result := &map[int64]*PushData{}
  187. for k, v := range *users {
  188. (*result)[common.Int64All(v["id"])] = &PushData{
  189. PersonName: fmt.Sprintf("%s_%d", common.InterfaceToStr(v["name"]), k),
  190. DepartmentName: common.InterfaceToStr(v["dept_name"]),
  191. entUserId: common.InterfaceToStr(v["id"]),
  192. }
  193. }
  194. if data != nil && len(*data) > 0 {
  195. for _, v := range *data {
  196. userId := int64(0)
  197. if isAdmin {
  198. userId = common.Int64All(v["ent_user_id"])
  199. } else {
  200. userId = common.Int64All(v["position_id"])
  201. }
  202. if (*result)[userId] != nil {
  203. //浏览总数处理处理
  204. project_id := common.InterfaceToStr(common.InterfaceToStr(v["project_id"]))
  205. if common.Int64All(v["isvisit"]) > 0 {
  206. (*result)[userId].BrowseNumb = DataHanle((*result)[userId].BrowseNumb, project_id)
  207. }
  208. //推送总数处理
  209. (*result)[userId].PushNumb = DataHanle((*result)[userId].PushNumb, project_id)
  210. //参标总数处理
  211. if common.Int64All(v["isparticipate"]) > 0 {
  212. (*result)[userId].ParticipateNumb = DataHanle((*result)[userId].ParticipateNumb, project_id)
  213. }
  214. //投标总数处理
  215. if common.Int64All(v["isbid"]) > 0 {
  216. (*result)[userId].BidNumb = DataHanle((*result)[userId].BidNumb, project_id)
  217. }
  218. //中标总数处理
  219. if common.Int64All(v["win_status"]) != 0 {
  220. win_status := common.Int64All(v["win_status"])
  221. if win_status == 1 {
  222. (*result)[userId].WinNumb = DataHanle((*result)[userId].WinNumb, project_id)
  223. } else {
  224. delete((*result)[userId].WinNumb, project_id)
  225. }
  226. }
  227. }
  228. }
  229. }
  230. pushStatisticsList := make([]*bxcore.PushStatisticsData, len(*result))
  231. for _, v := range *result {
  232. personName := strings.Split(v.PersonName, "_")[0]
  233. k := common.Int64All(strings.Split(v.PersonName, "_")[1])
  234. pushStatisticsList[k] = &bxcore.PushStatisticsData{
  235. PersonName: personName,
  236. DepartmentName: v.DepartmentName,
  237. EntUserId: encrypt.SE.Encode2Hex(v.entUserId),
  238. PushNumb: common.Int64All(len(v.PushNumb)),
  239. ParticipateNumb: common.Int64All(len(v.ParticipateNumb)),
  240. BidNumb: common.Int64All(len(v.BidNumb)),
  241. WinNumb: common.Int64All(len(v.WinNumb)),
  242. BrowseNumb: common.Int64All(len(v.BrowseNumb)),
  243. }
  244. }
  245. return pushStatisticsList
  246. }
  247. func ProjectHandle(data *[]map[string]interface{}, users *[]map[string]interface{}, isAdmin bool) []*bxcore.ProjectStatisticsData {
  248. result := &map[int64]*ProjectData{}
  249. for k, v := range *users {
  250. (*result)[common.Int64All(v["id"])] = &ProjectData{
  251. PersonName: fmt.Sprintf("%s_%d", common.InterfaceToStr(v["name"]), k),
  252. DepartmentName: common.InterfaceToStr(v["dept_name"]),
  253. entUserId: common.InterfaceToStr(v["id"]),
  254. }
  255. }
  256. if data != nil && len(*data) > 0 {
  257. // existProject 已经存在的项目 项目id_用户id
  258. existProject := map[string]struct{}{}
  259. for _, v := range *data {
  260. userId := int64(0)
  261. if isAdmin {
  262. userId = common.Int64All(v["ent_user_id"])
  263. } else {
  264. userId = common.Int64All(v["position_id"])
  265. }
  266. project_id := common.InterfaceToStr(common.InterfaceToStr(v["project_id"]))
  267. if (*result)[userId] != nil {
  268. // 参标数量
  269. (*result)[userId].participateProjectNumb = DataHanle((*result)[userId].participateProjectNumb, project_id)
  270. //投标数量
  271. if common.Int64All(v["isbid"]) > 0 {
  272. (*result)[userId].BidNumb = DataHanle((*result)[userId].BidNumb, project_id)
  273. }
  274. //终止参保统计
  275. if common.Int64All(v["isend"]) != 0 {
  276. (*result)[userId].EndNumb = DataHanle((*result)[userId].EndNumb, project_id)
  277. }
  278. /* p408 调整:
  279. 这里是因为participate_project_statistics 表的数据是多条的
  280. 统计各阶段数据的时候和中标总数的时候只以最新的为准
  281. 但是统计各阶段勾选数量时 重复统计后续删除不好处理 所以这里调整为
  282. 查询的时候根据时间倒序,同一个项目只统计第一条就可以了 每个项目第一条就是当前阶段内最新的
  283. 其他的直接跳过 不用重复统计后续再删除
  284. */
  285. existKey := fmt.Sprintf("%d_%s", userId, project_id)
  286. if _, ok := existProject[existKey]; !ok {
  287. existProject[existKey] = struct{}{}
  288. } else {
  289. continue
  290. }
  291. //直接投标数
  292. if common.Int64All(v["bid_way"]) > 0 {
  293. if common.Int64All(v["bid_way"]) == 2 {
  294. (*result)[userId].ChannelBidNumb = DataHanle((*result)[userId].ChannelBidNumb, project_id)
  295. delete((*result)[userId].DirectBidNumb, project_id)
  296. } else {
  297. (*result)[userId].DirectBidNumb = DataHanle((*result)[userId].DirectBidNumb, project_id)
  298. delete((*result)[userId].ChannelBidNumb, project_id)
  299. }
  300. }
  301. //中标总数处理
  302. if common.Int64All(v["win_status"]) != 0 {
  303. if common.Int64All(v["win_status"]) > 0 {
  304. //中标数量
  305. (*result)[userId].WinNumb = DataHanle((*result)[userId].WinNumb, project_id)
  306. delete((*result)[userId].NotBidNumber, project_id)
  307. } else {
  308. //未中标数量
  309. (*result)[userId].NotBidNumber = DataHanle((*result)[userId].NotBidNumber, project_id)
  310. delete((*result)[userId].WinNumb, project_id)
  311. }
  312. }
  313. //中标方式处理
  314. if common.Int64All(v["win_bidway"]) != 0 {
  315. if common.Int64All(v["win_bidway"]) == 1 {
  316. //直接投标数量
  317. (*result)[userId].DirectWinNumb = DataHanle((*result)[userId].DirectWinNumb, project_id)
  318. delete((*result)[userId].ChannelWinNumb, project_id)
  319. } else {
  320. //渠道投标数量
  321. (*result)[userId].ChannelWinNumb = DataHanle((*result)[userId].ChannelWinNumb, project_id)
  322. delete((*result)[userId].DirectWinNumb, project_id)
  323. }
  324. }
  325. // 阶段勾选数量统计 只统计第一条
  326. stage := common.ObjToString(v["bid_stage"])
  327. if stage != "" {
  328. stageSplit := strings.Split(stage, ",")
  329. if (*result)[userId].Stage == nil {
  330. (*result)[userId].Stage = map[string]map[string]interface{}{}
  331. }
  332. for i := 0; i < len(stageSplit); i++ {
  333. stageK := stageSplit[i]
  334. (*result)[userId].Stage[stageK] = DataHanle((*result)[userId].Stage[stageSplit[i]], project_id)
  335. }
  336. }
  337. }
  338. }
  339. }
  340. projectStatisticsList := make([]*bxcore.ProjectStatisticsData, len(*result))
  341. for _, v := range *result {
  342. personName := strings.Split(v.PersonName, "_")[0]
  343. k := common.Int64All(strings.Split(v.PersonName, "_")[1])
  344. tmpStage := map[string]int64{}
  345. for stageK, stageV := range v.Stage {
  346. stage_ := fmt.Sprintf("%s(阶段)", stageK)
  347. tmpStage[stage_] = int64(len(stageV))
  348. }
  349. projectStatisticsList[k] = &bxcore.ProjectStatisticsData{
  350. PersonName: personName,
  351. DepartmentName: v.DepartmentName,
  352. EntUserId: encrypt.SE.Encode2Hex(v.entUserId),
  353. BidNumb: common.Int64All(len(v.BidNumb)),
  354. DirectBidNumb: common.Int64All(len(v.DirectBidNumb)),
  355. ChannelBidNumb: common.Int64All(len(v.ChannelBidNumb)),
  356. WinNumb: common.Int64All(len(v.WinNumb)),
  357. DirectWinNumb: common.Int64All(len(v.DirectWinNumb)),
  358. ChannelWinNumb: common.Int64All(len(v.ChannelWinNumb)),
  359. NotBidNumber: common.Int64All(len(v.NotBidNumber)),
  360. EndNumb: common.Int64All(len(v.EndNumb)),
  361. ParticipateProjectNumb: common.Int64All(len(v.participateProjectNumb)),
  362. Stage: tmpStage,
  363. }
  364. }
  365. return projectStatisticsList
  366. }
  367. func EntInfo(entId, entUserId int) *CurrentUser {
  368. currentUser := &CurrentUser{
  369. Dept: &Department{},
  370. }
  371. user := IC.MainMysql.SelectBySql(`SELECT a.name as user_name from entniche_user a INNER JOIN entniche_user_role b on (a.id=b.user_id) where a.id=? and b.role_id=? limit 1`, entUserId, Role_admin_system)
  372. if user != nil && len(*user) > 0 {
  373. currentUser.Role_admin_system = true
  374. currentUser.User_name, _ = (*user)[0]["user_name"].(string)
  375. currentUser.User_power = 1
  376. r := IC.MainMysql.SelectBySql(`SELECT id,name,subdis,nodiff from entniche_department where ent_id=? and pid=0 limit 1`, entId)
  377. if r != nil && len(*r) == 1 {
  378. department := JsonUnmarshal((*r)[0], &Department{}).(*Department)
  379. if department != nil {
  380. department.Pid = department.Id
  381. currentUser.Dept = department
  382. }
  383. }
  384. } else {
  385. //角色、权限
  386. r := IC.MainMysql.SelectBySql(`SELECT a.name as user_name,a.power as user_power,b.role_id,d.id as dept_id,d.name as dept_name,d.subdis as dept_subdis,d.nodiff as dept_nodiff,e.id as dept_pid from entniche_user a
  387. LEFT JOIN entniche_user_role b on (b.user_id=?)
  388. INNER JOIN entniche_department_user c on (a.id=? and a.id=c.user_id)
  389. INNER JOIN entniche_department d on (c.dept_id=d.id)
  390. INNER JOIN entniche_department e on (e.ent_id=? and e.pid=0)
  391. order by a.id desc limit 1`, entUserId, entUserId, entId)
  392. if r != nil && len(*r) == 1 {
  393. currentUser.User_name, _ = (*r)[0]["user_name"].(string)
  394. currentUser.User_power = common.IntAll((*r)[0]["user_power"])
  395. if common.IntAll((*r)[0]["role_id"]) == Role_admin_department {
  396. currentUser.Role_admin_department = true
  397. }
  398. currentUser.Dept.Id = common.IntAll((*r)[0]["dept_id"])
  399. currentUser.Dept.Pid = common.IntAll((*r)[0]["dept_pid"])
  400. currentUser.Dept.Name = common.ObjToString((*r)[0]["dept_name"])
  401. currentUser.Dept.Subdis = common.IntAll((*r)[0]["dept_subdis"])
  402. currentUser.Dept.Nodiff = common.IntAll((*r)[0]["dept_nodiff"])
  403. }
  404. }
  405. return currentUser
  406. }
  407. // map转结构体
  408. func JsonUnmarshal(m interface{}, s interface{}) interface{} {
  409. var b []byte
  410. if v, ok := m.(string); ok {
  411. b = []byte(v)
  412. } else if v, ok := m.([]byte); ok {
  413. b = v
  414. } else {
  415. b, _ = json.Marshal(m)
  416. }
  417. json.Unmarshal(b, &s)
  418. return s
  419. }
  420. // 获取部门下可以进行分发的人员(不包含部门名称和部门id)
  421. func GetDisUsers(entId, deptId int) *[]map[string]interface{} {
  422. r := IC.MainMysql.SelectBySql(`select DISTINCT c.id,c.name,c.phone,c.power,b.dept_id,d.name as dept_name
  423. from entniche_department_parent a
  424. INNER JOIN entniche_department_user b on (b.dept_id=? or (a.pid=? and a.id=b.dept_id))
  425. INNER JOIN entniche_user c on (c.ent_id=? and b.user_id=c.id)
  426. INNER JOIN entniche_department d on d.id=b.dept_id
  427. order by b.dept_id , convert(c.name using gbk) COLLATE gbk_chinese_ci asc`, deptId, deptId, entId)
  428. return r
  429. }
  430. func GetUser(entUserIdArr []string) *[]map[string]interface{} {
  431. r := IC.MainMysql.SelectBySql("SELECT DISTINCT a.id, a.name, a.phone, d.id AS dept_id, d.NAME AS dept_name " +
  432. "FROM entniche_user a " +
  433. " INNER JOIN entniche_department_user b ON FIND_IN_SET(a.id,'" + strings.Join(entUserIdArr, ",") +
  434. "') and b.user_id = a.id " +
  435. " INNER JOIN entniche_department d ON d.id = b.dept_id " +
  436. " ORDER BY d.id, CONVERT ( a.NAME USING gbk ) COLLATE gbk_chinese_ci ASC",
  437. )
  438. return r
  439. }
  440. type User struct {
  441. Id int
  442. Name string //员工姓名
  443. Mail string //邮箱
  444. Phone string //手机号
  445. Dept_id int //部门id
  446. Dept_name string //部门名称
  447. //Role string //角色
  448. Power int //权限
  449. }
  450. type CurrentUser struct {
  451. Role_admin_department bool //是否是部门管理员
  452. Role_admin_system bool //是否是系统管理员
  453. Dept *Department //部门信息
  454. BondPhone string //手机号
  455. NickName string //昵称
  456. HeadImageUrl string //头像
  457. PersonalAuth int //个人认证
  458. PersonalAuthReason string //个人认证不通过原因
  459. User_power int //是否分配权限
  460. User_name string //用户姓名
  461. }
  462. type Department struct {
  463. Id int
  464. Name string //部门名
  465. Pid int //上级部门id
  466. Pname string //上级部门名称
  467. Nodiff int //全员无差别接收 0:关闭 1:打开
  468. Subdis int //订阅分发 0:关闭 1:打开
  469. Aid int //管理员id
  470. Aname string //管理员姓名
  471. Rname string //角色名
  472. User_count int //该部门下员工的总数
  473. Dept_count int //该部门下子部门总数
  474. Ent_id int //公司id
  475. }
  476. func DataHanle(data map[string]interface{}, project_id string) map[string]interface{} {
  477. if data == nil {
  478. data = map[string]interface{}{project_id: 1}
  479. } else {
  480. data[project_id] = 1
  481. }
  482. return data
  483. }
  484. func QueryHandle(isAdmin bool, startTime, endTime int64, personArrStr string, source []int64, bidWay int64) []string {
  485. //时间处理
  486. query := []string{}
  487. if isAdmin {
  488. //是管理员
  489. query = append(query, fmt.Sprintf(" ent_user_id in (%s) ", personArrStr))
  490. } else {
  491. //不是管理员
  492. query = append(query, fmt.Sprintf(" position_id = %s ", personArrStr))
  493. }
  494. if startTime == 0 && endTime == 0 {
  495. //没有传时间,默认时间处理
  496. var start = time.Now().AddDate(0, 0, -30)
  497. query = append(query, fmt.Sprintf(" ymd >= %s ", start.Format("20060102")))
  498. }
  499. if startTime != 0 {
  500. query = append(query, fmt.Sprintf(" ymd >= %d ", startTime))
  501. }
  502. if endTime != 0 {
  503. query = append(query, fmt.Sprintf(" ymd <= %d ", endTime))
  504. }
  505. if len(source) > 0 {
  506. sourceArr := []string{}
  507. for i := 0; i < len(source); i++ {
  508. sourceArr = append(sourceArr, fmt.Sprintf(" FIND_IN_SET('%d', a.source)", source[i]))
  509. }
  510. query = append(query, fmt.Sprintf(" (%s) ", strings.Join(sourceArr, " or ")))
  511. }
  512. if bidWay != 0 {
  513. query = append(query, fmt.Sprintf("bid_way = %d", bidWay))
  514. }
  515. return query
  516. }
  517. func (in *ParticipateStatistics) ProjectDetails(entUserIdArr []string, detailReq *bxcore.ProjectDetailsReq) (result bxcore.DetailData) {
  518. //判断是企业、部门还是个人
  519. isAdmin, personArrStr, _ := in.PersonHandle(entUserIdArr)
  520. queryType := GetQueryType(detailReq)
  521. query, countQuery := GetDetailQuery(isAdmin, personArrStr, detailReq, queryType)
  522. totalCount := IC.BaseMysql.CountBySql(countQuery)
  523. if totalCount <= 0 {
  524. return
  525. }
  526. // 处理数据 这里只是筛选出项目id和阶段信息
  527. dataList := IC.BaseMysql.SelectBySql(query)
  528. if dataList == nil || len(*dataList) == 0 {
  529. return
  530. }
  531. // 处理数据 补充项目名称、推送表字段 、格式化数据
  532. rs := ProjectDetailHandle(*dataList, in.EntId, int(detailReq.PositionId), int(detailReq.PositionType))
  533. result = bxcore.DetailData{
  534. List: rs,
  535. Total: totalCount,
  536. }
  537. // 处理数据
  538. return
  539. }
  540. // todo 查询条件验证
  541. //
  542. // 这个查询只用查出符合筛选条件的项目id 以及该项目对应的stage
  543. // 查询类型 0空搜索 全连接 1查左边 连右表查stage 2只查右表 3内连接
  544. func GetDetailQuery(isAdmin bool, personArrStr string, req *bxcore.ProjectDetailsReq, queryType int) (string, string) {
  545. // 处理分页
  546. if req.PageNum == 0 && req.PageSize == 0 {
  547. req.PageNum = 1
  548. req.PageSize = 50
  549. }
  550. // 这是因为数据库中 0是未参标 1是已参标, 接收参数时和其他默认参数保持一致 0-全部 1 是未参标 2 是已参标
  551. req.IsParticipate -= 1
  552. if queryType == 0 {
  553. // 空搜索调整
  554. query1, query2 := []string{}, []string{}
  555. query3 := ""
  556. //没有传时间,默认时间处理
  557. var start = time.Now().AddDate(0, 0, -30)
  558. query1 = append(query1, fmt.Sprintf(" a.ymd >= %s ", start.Local().Format("20060102")))
  559. query2 = append(query2, fmt.Sprintf(" b.update_date >= '%s' ", start.Local().Format(date.Date_Full_Layout)))
  560. if isAdmin {
  561. //是管理员
  562. query1 = append(query1, fmt.Sprintf(" a.ent_user_id in (%s) ", personArrStr))
  563. personArr := []string{}
  564. personArrStrSplit := strings.Split(personArrStr, ",")
  565. for i := 0; i < len(personArrStrSplit); i++ {
  566. personArr = append(personArr, fmt.Sprintf(" FIND_IN_SET('%s', b.ent_user_ids)", personArrStrSplit[i]))
  567. }
  568. if len(personArr) > 0 {
  569. personStr := strings.Join(personArr, " or ")
  570. query2 = append(query2, fmt.Sprintf(" (%s)", personStr))
  571. }
  572. query3 = fmt.Sprintf("b.ent_id='%d'", req.EntId) // 连接时右表的条件
  573. } else {
  574. //不是管理员
  575. query1 = append(query1, fmt.Sprintf(" a.position_id = %s ", personArrStr))
  576. personArr := []string{}
  577. personArrStrSplit := strings.Split(personArrStr, ",")
  578. for i := 0; i < len(personArrStrSplit); i++ {
  579. personArr = append(personArr, fmt.Sprintf(" FIND_IN_SET('%s', b.position_ids)", personArrStrSplit[i]))
  580. }
  581. if len(personArr) > 0 {
  582. personStr := strings.Join(personArr, " or ")
  583. query2 = append(query2, fmt.Sprintf(" (%s)", personStr))
  584. }
  585. if req.PositionType > 0 {
  586. query3 = fmt.Sprintf("b.ent_id='%d'", req.EntId) // 连接时右表的条件
  587. } else {
  588. query3 = fmt.Sprintf("b.position_ids='%d'", req.PositionId) // 连接时右表的条件
  589. }
  590. }
  591. q := `SELECT A.project_id, B.stage
  592. FROM
  593. (SELECT DISTINCT(project_id)
  594. FROM
  595. (SELECT project_id FROM participate_push_statistics a
  596. WHERE %s UNION
  597. SELECT project_id
  598. FROM participate_stage_statistics b
  599. WHERE %s) order by project_id
  600. LIMIT %d , %d) A
  601. LEFT JOIN
  602. participate_stage_statistics B ON A.project_id = B.project_id and %s` // and 连接前对右表过滤
  603. q2 := "select count(project_id) from (select distinct(project_id) from participate_push_statistics a where %s union select project_id from participate_stage_statistics b where %s )"
  604. q1Str := strings.Join(query1, " and ")
  605. q2Str := strings.Join(query2, " and ")
  606. return fmt.Sprintf(q, q1Str, q2Str, (req.PageNum-1)*req.PageSize, req.PageSize, query3), fmt.Sprintf(q2, q1Str, q2Str)
  607. }
  608. var q, qCount string
  609. query := []string{}
  610. joinStr := ""
  611. if queryType == 1 {
  612. if isAdmin {
  613. //是管理员
  614. query = append(query, fmt.Sprintf(" a.ent_user_id in (%s) ", personArrStr))
  615. joinStr = "and a.ent_id = b.ent_id"
  616. } else {
  617. query = append(query, fmt.Sprintf(" a.position_id = %s ", personArrStr))
  618. //不是管理员
  619. // 个人版
  620. if req.PositionType == 0 {
  621. joinStr = "and a.position_id = b.position_ids"
  622. } else {
  623. // 企业版 个人 因为是查项目的最新状态信息 所以 用ent_id 和项目id连表
  624. joinStr = "and a.ent_id = b.ent_id"
  625. }
  626. }
  627. //if req.StartTime == 0 && req.EndTime == 0 {
  628. // //没有传时间,默认时间处理
  629. // var start = time.Now().AddDate(0, 0, -30)
  630. // query = append(query, fmt.Sprintf(" a.ymd >= %s ", start.Local().Format("20060102")))
  631. //}
  632. if req.StartTime != 0 {
  633. query = append(query, fmt.Sprintf(" a.ymd >= %d ", req.StartTime))
  634. }
  635. if req.EndTime != 0 {
  636. query = append(query, fmt.Sprintf(" a.ymd < %d ", req.EndTime))
  637. }
  638. // 标讯/项目来源
  639. if len(req.Source) > 0 {
  640. sourceArr := []string{}
  641. for i := 0; i < len(req.Source); i++ {
  642. if req.Source[i] == 0 {
  643. sourceArr = append(sourceArr, fmt.Sprintf(" FIND_IN_SET('%d', a.source)", 1))
  644. sourceArr = append(sourceArr, fmt.Sprintf(" FIND_IN_SET('%d', a.source)", 2))
  645. } else {
  646. sourceArr = append(sourceArr, fmt.Sprintf(" FIND_IN_SET('%d', a.source)", req.Source[i]))
  647. }
  648. }
  649. query = append(query, fmt.Sprintf(" (%s) ", strings.Join(sourceArr, " or ")))
  650. }
  651. // 投标类型 投标方式;1:直接投标 2:渠道投标',
  652. if req.BidWay != 0 {
  653. query = append(query, fmt.Sprintf("a.bid_way = %d", req.BidWay))
  654. }
  655. //参标状态:-1全部,0未参标、1已参标
  656. if req.IsParticipate != -1 {
  657. query = append(query, fmt.Sprintf("a.isparticipate = %d", req.IsParticipate))
  658. }
  659. q = "select distinct(a.project_id),b.stage,a.ymd,b.update_date from participate_push_statistics a left join participate_stage_statistics b on(a.project_id=b.project_id %s ) where %s order by a.ymd desc,b.update_date desc"
  660. qCount = "select count(distinct(a.project_id)) from participate_push_statistics a left join participate_stage_statistics b on(a.project_id=b.project_id %s) where %s"
  661. } else if queryType == 2 {
  662. if isAdmin {
  663. //是管理员
  664. personArr := []string{}
  665. personArrStrSplit := strings.Split(personArrStr, ",")
  666. for i := 0; i < len(personArrStrSplit); i++ {
  667. personArr = append(personArr, fmt.Sprintf(" FIND_IN_SET('%s', b.ent_user_ids)", personArrStrSplit[i]))
  668. }
  669. if len(personArr) > 0 {
  670. personStr := strings.Join(personArr, " or ")
  671. query = append(query, fmt.Sprintf("(%s)", personStr))
  672. }
  673. } else {
  674. //不是管理员
  675. query = append(query, fmt.Sprintf(" FIND_IN_SET('%s', b.position_ids)", personArrStr))
  676. }
  677. //// 无默认时间时
  678. //if req.BidUpdateStartTime == 0 && req.BidUpdateEndTime == 0 {
  679. // var start = time.Now().AddDate(0, 0, -30)
  680. // query = append(query, fmt.Sprintf(" b.update_date >= '%s' ", start.Local().Format(date.Date_Full_Layout)))
  681. //}
  682. // 参标状态更新时间
  683. if req.BidUpdateStartTime != 0 {
  684. bidStart_, err := time.ParseInLocation(date.Date_yyyyMMdd, fmt.Sprintf("%d", req.BidUpdateStartTime), time.Local)
  685. if err != nil {
  686. bidStart_ = time.Now().AddDate(0, 0, -30)
  687. log.Println("时间转换失败,使用默认值:", err)
  688. }
  689. bidStart := date.FormatDate(&bidStart_, date.Date_Full_Layout)
  690. query = append(query, fmt.Sprintf("b.update_date >= '%s'", bidStart))
  691. }
  692. if req.BidUpdateEndTime != 0 {
  693. bidEnd_, err := time.ParseInLocation(date.Date_yyyyMMdd, fmt.Sprintf("%d", req.BidUpdateEndTime), time.Local)
  694. if err != nil {
  695. bidEnd_ = time.Now().AddDate(0, 0, -30)
  696. log.Println("时间转换失败,使用默认值:", err)
  697. }
  698. bidEnd := date.FormatDate(&bidEnd_, date.Date_Full_Layout)
  699. query = append(query, fmt.Sprintf("b.update_date < '%s'", bidEnd))
  700. }
  701. if req.BidWay != 0 {
  702. query = append(query, fmt.Sprintf("b.bid_way = %d", req.BidWay))
  703. }
  704. //参标状态:-1全部,0未参标、1已参标
  705. if req.IsParticipate == 1 {
  706. query = append(query, fmt.Sprintf("b.isparticipate = %d", req.IsParticipate))
  707. }
  708. q = "select b.project_id,b.stage from participate_stage_statistics b where %s %s order by b.update_date desc"
  709. qCount = "select count(b.project_id) from participate_stage_statistics b where %s %s"
  710. } else {
  711. if isAdmin {
  712. //是管理员
  713. query = append(query, fmt.Sprintf(" a.ent_user_id in (%s) ", personArrStr))
  714. joinStr = "and a.ent_id = b.ent_id"
  715. } else {
  716. query = append(query, fmt.Sprintf(" a.position_id = %s ", personArrStr))
  717. //不是管理员
  718. // 个人版
  719. if req.PositionType == 0 {
  720. joinStr = "and a.position_id = b.position_ids"
  721. } else {
  722. // 企业版 个人 因为是查项目的最新状态信息 所以 用ent_id 和项目id连表
  723. joinStr = "and a.ent_id = b.ent_id"
  724. }
  725. }
  726. if req.StartTime != 0 {
  727. query = append(query, fmt.Sprintf(" a.ymd >= %d ", req.StartTime))
  728. }
  729. if req.EndTime != 0 {
  730. query = append(query, fmt.Sprintf(" a.ymd < %d ", req.EndTime))
  731. }
  732. if len(req.Source) > 0 {
  733. sourceArr := []string{}
  734. for i := 0; i < len(req.Source); i++ {
  735. if req.Source[i] == 0 {
  736. sourceArr = append(sourceArr, fmt.Sprintf(" FIND_IN_SET('%d', a.source)", 1))
  737. sourceArr = append(sourceArr, fmt.Sprintf(" FIND_IN_SET('%d', a.source)", 2))
  738. } else {
  739. sourceArr = append(sourceArr, fmt.Sprintf(" FIND_IN_SET('%d', a.source)", req.Source[i]))
  740. }
  741. }
  742. query = append(query, fmt.Sprintf(" (%s) ", strings.Join(sourceArr, " or ")))
  743. }
  744. //参标状态:-1全部,0未参标、1已参标
  745. if req.IsParticipate != -1 {
  746. query = append(query, fmt.Sprintf("a.isparticipate = %d", req.IsParticipate))
  747. }
  748. // 投标类型 投标方式;1:直接投标 2:渠道投标',
  749. if req.BidWay != 0 {
  750. query = append(query, fmt.Sprintf("a.bid_way = %d", req.BidWay))
  751. }
  752. // 参标状态更新时间
  753. if req.BidUpdateStartTime != 0 {
  754. bidStart_, err := time.ParseInLocation(date.Date_yyyyMMdd, fmt.Sprintf("%d", req.BidUpdateStartTime), time.Local)
  755. if err != nil {
  756. bidStart_ = time.Now().AddDate(0, 0, -30)
  757. log.Println("时间转换失败,使用默认值:", err)
  758. }
  759. bidStart := date.FormatDate(&bidStart_, date.Date_Full_Layout)
  760. query = append(query, fmt.Sprintf("b.update_date >= '%s'", bidStart))
  761. }
  762. if req.BidUpdateEndTime != 0 {
  763. bidEnd_, err := time.ParseInLocation(date.Date_yyyyMMdd, fmt.Sprintf("%d", req.BidUpdateEndTime), time.Local)
  764. if err != nil {
  765. bidEnd_ = time.Now().AddDate(0, 0, -30)
  766. log.Println("时间转换失败,使用默认值:", err)
  767. }
  768. bidEnd := date.FormatDate(&bidEnd_, date.Date_Full_Layout)
  769. query = append(query, fmt.Sprintf("b.update_date < '%s'", bidEnd))
  770. }
  771. q = "select distinct(a.project_id),b.stage,a.ymd,b.update_date from participate_push_statistics a inner join participate_stage_statistics b on(b.project_id=a.project_id %s) where %s order by a.ymd desc,b.update_date desc"
  772. qCount = "select count(distinct(a.project_id)) from participate_push_statistics a inner join participate_stage_statistics b on(b.project_id=a.project_id %s) where %s"
  773. }
  774. if len(query) > 0 {
  775. q = fmt.Sprintf(q, joinStr, strings.Join(query, " and "))
  776. qCount = fmt.Sprintf(qCount, joinStr, strings.Join(query, " and "))
  777. }
  778. q = fmt.Sprintf("%s limit %d,%d", q, (req.PageNum-1)*req.PageSize, req.PageSize)
  779. return q, qCount
  780. }
  781. type PushInfoStruct struct {
  782. Source string
  783. VisitDate string
  784. DisDate string
  785. IsDistribute int
  786. }
  787. func ProjectDetailHandle(dataList []map[string]interface{}, entId int64, positionId, positionType int) []*bxcore.ProjectDetailData {
  788. //dataList 里面包含 项目id、各阶段信息
  789. // 处理项目名称
  790. projectIdList := []string{}
  791. for i := 0; i < len(dataList); i++ {
  792. projectIdList = append(projectIdList, common.ObjToString(dataList[i]["project_id"]))
  793. }
  794. // 项目名称处理成map用于后续使用
  795. projectNameMap := map[string]string{}
  796. projectNameRs := es.GetProjectNameByProjectId(projectIdList)
  797. if projectNameRs != nil && len(*projectNameRs) > 0 {
  798. for i := 0; i < len(*projectNameRs); i++ {
  799. projectId_ := common.ObjToString((*projectNameRs)[i]["_id"])
  800. projectName_ := (*projectNameRs)[i]["projectname"]
  801. projectNameMap[projectId_] = common.ObjToString(projectName_)
  802. }
  803. }
  804. // 获取推送最新状态
  805. newPushInfo := getNewPushInfo(projectIdList, int(entId), positionId, positionType)
  806. newPushInfoMap := map[string]PushInfoStruct{}
  807. // 处理推送最新状态
  808. if newPushInfo != nil && len(*newPushInfo) > 0 {
  809. for i := 0; i < len(*newPushInfo); i++ {
  810. project_ := common.ObjToString((*newPushInfo)[i]["project_id"])
  811. info := PushInfoStruct{
  812. Source: common.ObjToString((*newPushInfo)[i]["source"]),
  813. VisitDate: common.ObjToString((*newPushInfo)[i]["visit_date"]),
  814. DisDate: common.ObjToString((*newPushInfo)[i]["dis_date"]),
  815. }
  816. newPushInfoMap[project_] = info
  817. }
  818. }
  819. results := []*bxcore.ProjectDetailData{}
  820. // 处理成最后的数据
  821. for i := 0; i < len(dataList); i++ {
  822. projectId := common.ObjToString(dataList[i]["project_id"])
  823. tmp := bxcore.ProjectDetailData{
  824. ProjectName: projectNameMap[projectId],
  825. }
  826. isDistribute_ := ""
  827. // 处理推送表相关字段
  828. if pushInfo_, ok := newPushInfoMap[projectId]; ok {
  829. sourceStr := []string{}
  830. if pushInfo_.Source != "" {
  831. isDistribute_ = "未分发"
  832. sourceSplit := strings.Split(pushInfo_.Source, ",")
  833. for j := 0; j < len(sourceSplit); j++ {
  834. if sourceSplit[j] == "3" {
  835. isDistribute_ = "已分发"
  836. }
  837. if sourceName, ok := SourceMap[sourceSplit[j]]; ok {
  838. sourceStr = append(sourceStr, sourceName)
  839. }
  840. }
  841. }
  842. tmp.Source = strings.Join(sourceStr, ",") // 处理成中文
  843. tmp.ViewDate = pushInfo_.VisitDate
  844. tmp.IsDistribute = isDistribute_
  845. tmp.DisDate = pushInfo_.DisDate
  846. } //
  847. // 处理阶段勾选信息和参标、终止参标信息
  848. if dataList[i]["stage"] != nil {
  849. if stage_, err := json.Marshal(*common.ObjToMap(dataList[i]["stage"])); err == nil {
  850. err := json.Unmarshal(stage_, &tmp.Stage)
  851. if err != nil {
  852. log.Println("stage 反序列失败", err)
  853. }
  854. }
  855. }
  856. tmp.Id = encrypt.EncodeArticleId2ByCheck(projectId)
  857. results = append(results, &tmp)
  858. }
  859. return results
  860. }
  861. // 获取项目的最新推送状态信息
  862. func getNewPushInfo(projectIds []string, entId int, positionId int, positionType int) *[]map[string]interface{} {
  863. s := ""
  864. if positionType == 0 {
  865. s = fmt.Sprintf("position_id=%d", positionId)
  866. } else {
  867. s = fmt.Sprintf("ent_id=%d", entId)
  868. }
  869. sql := `
  870. SELECT
  871. A.project_id, A.source, A.visit_date, A.dis_date, A.is_distribute,A.id,A.ymd,B.ymd
  872. FROM participate_push_statistics A inner join (SELECT
  873. project_id,MAX(ymd) as ymd
  874. FROM
  875. participate_push_statistics
  876. WHERE
  877. %s
  878. AND project_id IN ( "` + strings.Join(projectIds, "\",\"") + `" )
  879. GROUP BY project_id) B on (A.project_id=B.project_id and A.ymd=b.ymd) where A.%s
  880. `
  881. query := fmt.Sprintf(sql, s, s)
  882. return IC.BaseMysql.SelectBySql(query)
  883. }
  884. // GetQueryType 查询类型 0空搜索 全连接 1查左边 连右表查stage 2只查右表 3内连接
  885. // IsParticipate 接收参数时 0 全部 1 未参标 2已参标 数据库中 未参标是0
  886. func GetQueryType(in *bxcore.ProjectDetailsReq) int {
  887. // TODO 调整
  888. if in.BidUpdateStartTime == 0 && in.BidUpdateEndTime == 0 && in.StartTime == 0 && in.EndTime == 0 && in.IsParticipate == 0 && in.BidWay == 0 && len(in.Source) == 0 {
  889. return 0
  890. }
  891. if in.IsParticipate == 1 {
  892. // 未参标只筛选推送表 右表条件无效
  893. return 1
  894. }
  895. if (in.StartTime != 0 || in.EndTime != 0 || len(in.Source) > 0) && (in.BidUpdateStartTime == 0 && in.BidUpdateEndTime == 0 && in.IsParticipate != 2) {
  896. return 1
  897. }
  898. if (in.StartTime == 0 && in.EndTime == 0 && len(in.Source) == 0) && (in.BidUpdateStartTime != 0 || in.BidUpdateEndTime == 0 || in.IsParticipate == 2 || in.BidWay != 0) {
  899. return 2
  900. }
  901. return 3
  902. }