Commit e9ab53f2 by liimin

完善定时任务

1 parent 4ec80cd2
...@@ -2,9 +2,10 @@ ...@@ -2,9 +2,10 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:20:15 * @Date: 2019-11-21 11:20:15
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-11-26 15:58:28 * @Last Modified time: 2019-11-28 15:16:50
*/ */
module.exports = { module.exports = {
PREFIX: '_glsx_data_screen_' PREFIX: '_glsx_data_screen_',
USER_SUMMARY_YESTERDAY:'user_summary_yesterday'
}; };
\ No newline at end of file \ No newline at end of file
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:20:01 * @Date: 2019-11-21 11:20:01
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-11-27 19:11:39 * @Last Modified time: 2019-11-28 18:11:13
*/ */
"use strict"; "use strict";
...@@ -29,15 +29,22 @@ class UserController extends Controller { ...@@ -29,15 +29,22 @@ class UserController extends Controller {
* @Description 数据大屏-用户总数统计.----参数pid 有 则返回对应的省份数据.没有则是全国数据的统计 * @Description 数据大屏-用户总数统计.----参数pid 有 则返回对应的省份数据.没有则是全国数据的统计
* @Request query integer pid 省份id * @Request query integer pid 省份id
*/ */
async total({ query: { pid } }) { async total({ query: { pid,cid} }) {
var statics = await this.UserService.user_summary_provice_by_day(this.helper.date(-1),pid) var yesterday_total = await this.CacheService.get(this.helper.constant.USER_SUMMARY_YESTERDAY);
var { total, province } = yesterday_total
if (pid) {
var obj = cid ? province[pid]["city"][cid] : province[pid];
total = obj ? obj.total : 0;
}
const today_total = await this.UserService.last_n_day_user_increased({n:0,pid,cid});
total += ~~today_total;
// console.log(this.app.cache.today); // console.log(this.app.cache.today);
// `user_summary_${day}` // `user_summary_${day}`
// const data = await this.CacheService.get("test", () => // const data = await this.CacheService.get("test", () =>
// this.DemoService.hello(this.request.body) // this.DemoService.hello(this.request.body)
// ); // );
// const statics = await this.UserService.total(pid); // const statics = await this.UserService.total(pid);
const data = { statics }; const data = { total };
this.ctx.body = this.ServerResponse.Success(data); this.ctx.body = this.ServerResponse.Success(data);
} }
/** /**
...@@ -45,18 +52,23 @@ class UserController extends Controller { ...@@ -45,18 +52,23 @@ class UserController extends Controller {
* @Description 数据大屏-数据统计 1. 近七天新增用户数 2.近七天用户活跃度 3.近30天用户留存率 4.用户付费转化率 * @Description 数据大屏-数据统计 1. 近七天新增用户数 2.近七天用户活跃度 3.近30天用户留存率 4.用户付费转化率
* @Request query integer pid 省份id * @Request query integer pid 省份id
*/ */
async statistics({ query: { pid, n = 7 } }) { async statistics({ query: { pid, n = -7,cid } }) {
console.log( this.app.cache); await this.app.runSchedule('update_cache');
// console.log( await this.redis.set(`test_${this.helper.date(-1,'YYYY_MM_DD')}`,'aaa'));
console.log( await this.redis.get(`test_${this.helper.date(-1,'YYYY_MM_DD')}`));
// this.validate({ n: 'userName' },{ pid, n});
//近7天新增用户数 //近7天新增用户数
const increased = await this.UserService.last_n_day_user_increased(pid, n); const increased7 = await this.UserService.last_n_day_user_increased({n,pid,cid});
//近七天 活跃用户数 //近七天 活跃用户数
const nLive = await this.UserService.last_n_day_user_lively(pid, n); const nLive7 = await this.UserService.last_n_day_user_lively({n,pid,cid});
// 近七天 用户活跃度 (近N天 活跃用户数 / 近N天新增用户数) // 近七天 用户活跃度 (近N天 活跃用户数 / 近N天新增用户数)
const live = ((nLive / increased) * 100).toFixed(2) + "%"; const live7 = ((~~nLive7 / ~~increased7) * 100).toFixed(2)+ "%";
const data = { increased, live };
//近30天新增用户数
const increased30 = await this.UserService.last_n_day_user_increased({n:-30,pid,cid});
//近30天 活跃用户数
const nLive30 = await this.UserService.last_n_day_user_lively({n:-30,pid,cid});
// 近30天 用户活跃度 (近N天 活跃用户数 / 近N天新增用户数)
const live30 = ((~~nLive30 / ~~increased30) * 100).toFixed(2)+ "%";
const data = { increased7, live7,increased30,live30 };
this.ctx.body = this.ServerResponse.Success(data); this.ctx.body = this.ServerResponse.Success(data);
} }
......
...@@ -2,40 +2,60 @@ ...@@ -2,40 +2,60 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:19:43 * @Date: 2019-11-21 11:19:43
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-11-27 19:10:48 * @Last Modified time: 2019-11-28 16:22:53
*/ */
const moment = require("moment"); const moment = require("moment");
const constant = require("../common/constant"); const constant = require("../common/constant");
// exports.relativeTime = time => moment(new Date(time * 1000)).fromNow(); // exports.relativeTime = time => moment(new Date(time * 1000)).fromNow();
exports.date = (n, f = "YYYY-MM-DD") => exports.date = (n, f = "YYYY-MM-DD") =>moment().add(n, "days").format(f);
moment() /**
.add(n, "days") * 结束日期格式化函数
.format(f); */
exports.formatEndDate =end=>`${end} 23:59:59`;
/**
* 字符串转json 如果是json字符串 返回json对象 如果不是JSON字符串 返回原始字符串
*/
exports.jsonParser =str=>{
var res;
try {
res = JSON.parse(str)
} catch (error) {
res = str
}
return res
}
/** /**
* 简单封装 sequelize 查询参数 * 简单封装 sequelize 查询参数
*/ */
exports.seqOption = function({ pid, n, limit, order, day,beginDate,endDate }) { exports.seqOption = function({ pid,cid, n, limit, order, day,beginDate,endDate }) {
let where = {}; let where = {};
const { between } = this.ctx.app.Sequelize.Op; const { between } = this.ctx.app.Sequelize.Op;
if (pid) { if (cid) {
where.city_code = cid;
}else if (pid){
where.prov_code = pid; where.prov_code = pid;
} }
if (day) { if (day) {
//如果有具体天数 就直接查询具体一天的数据(优先具体哪一天) //如果有具体天数 就直接查询具体一天的数据(优先具体哪一天)
where.day = day; where.day = day;
} else if (n || n === 0) { } else if (n) {
// 查询近N天的数据 0 表示当天 // 查询近N天的数据 不包括今天
where.day = {
[between]: [this.date(n), this.formatEndDate(this.date(-1))]
};
} else if (n === 0) {
// 查询
where.day = { where.day = {
[between]: [this.date(-n), this.date(0)] [between]: [this.date(0), this.formatEndDate(this.date(0))]
}; };
} else if(beginDate){ } else if(beginDate){
if(!endDate){ if(!endDate){
endDate = beginDate endDate = beginDate
} }
if(!endDate.includes(':')){ if(!endDate.includes(':')){
endDate = `${endDate} 23:59:59` endDate = this.formatEndDate(endDate)
} }
where.day = { where.day = {
[between]: [beginDate, endDate] [between]: [beginDate, endDate]
......
...@@ -24,33 +24,64 @@ class UpdateCache extends Subscription { ...@@ -24,33 +24,64 @@ class UpdateCache extends Subscription {
// interval: '1m', // 定时任务 1 分钟间隔 // interval: '1m', // 定时任务 1 分钟间隔
cron: "0 33 9 * * *", // 定点任务 每天 凌晨 0点30 执行一次 cron: "0 33 9 * * *", // 定点任务 每天 凌晨 0点30 执行一次
type: "worker", // 随机 worker 执行 type: "worker", // 随机 worker 执行
immediate: true, //启动立即执行一次 immediate: true //启动立即执行一次
// disable:true // 不启动 // disable:true // 不启动
}; };
} }
_group(cities, f) {
const country = {
total:0,
date:'',
renew:0,
province:{}
};
cities.forEach(function (city) {
const prov_code = f(city);
let { city_code,total,city_name,prov_name,renew } = city
renew = +renew;
total = +total;
country.total += total;
country.renew += renew;
country['province'][prov_code] = country['province'][prov_code] || {}
if(!country['province'][prov_code]['name']){
country['province'][prov_code]['name']=prov_name;
country['province'][prov_code]['total']= 0;
}
country['province'][prov_code]['total'] += total;
country['province'][prov_code]['renew'] += renew;
// country['province'][prov_code]['city'] = country['province'][prov_code]['city'] || [];
// country['province'][prov_code]['city'].push({ city_code,total,city_name});
country['province'][prov_code]['city'] = country['province'][prov_code]['city'] || {};
country['province'][prov_code]['city'][city_code]={ total,city_name,renew };
});
return country
}
// subscribe 是真正定时任务执行时被运行的函数 // subscribe 是真正定时任务执行时被运行的函数
async subscribe() { async subscribe() {
this.logger.info('===============执行日常任务-缓存每日用户总数 begin==================') this.logger.info( "===============执行日常任务-缓存每日用户总数 begin==================");
const yesterday = this.helper.date(-1)
var total_yesterday = await this.UserService.user_summary_provice_by_day(this.helper.date(-1)) // 查询昨天 所有城市 分别 对应的 用户总数 列表
// if(total_yesterday.length){ const cities = await this.UserService.user_summary_city_by_day({beginDate:yesterday});
// total_yesterday.map(item=>) if (cities.length) {
// } const data = this._group(cities, city=>city.prov_code);
// const today_summary = await this.UserService.user_summary_today(); data.date = yesterday;
// if (today_summary.length) { const value = JSON.stringify(data);
// const [{ day, total }] = today_summary; await this.CacheService.set(
// const value = JSON.stringify({ day, total }); this.helper.constant.USER_SUMMARY_YESTERDAY,
// this.logger.info('today_summary:%s',value) value,
// await this.CacheService.set( 2 * 24 * 60 * 60 //两天过期
// `user_summary_${day}`, );
// value, this.logger.info("user_summary_%s:%s",yesterday,value);
// 25 * 60 * 60 //25小时有效 }else{
// ); this.logger.warn("warnning=============user_summary_yesterday===========is empty!");
// } }
this.app.cache = { this.app.cache = {
today: this.helper.date(0) today: this.helper.date(0),
yesterday
}; };
this.logger.info('===============执行日常任务-缓存每日用户总数 end==================') this.logger.info("===============执行日常任务-缓存每日用户总数 end==================");
} }
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 14:32:51 * @Date: 2019-11-21 14:32:51
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-11-26 16:37:00 * @Last Modified time: 2019-11-28 15:31:53
*/ */
"use strict"; "use strict";
...@@ -24,7 +24,11 @@ class CacheService extends Service { ...@@ -24,7 +24,11 @@ class CacheService extends Service {
async get(key, fnGetFromDB, ex) { async get(key, fnGetFromDB, ex) {
if (this.app.redis) { if (this.app.redis) {
return await this.app.redis.get(`${this.helper.constant.PREFIX}${key}`); var value = await this.app.redis.get(`${this.helper.constant.PREFIX}${key}`);
if(value){
value =this.helper.jsonParser(value)
return value
}
} }
if (fnGetFromDB) { if (fnGetFromDB) {
var data = await fnGetFromDB(); var data = await fnGetFromDB();
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: limin * @Author: limin
* @Date: 2019-11-21 11:18:37 * @Date: 2019-11-21 11:18:37
* @Last Modified by: limin * @Last Modified by: limin
* @Last Modified time: 2019-11-27 19:04:47 * @Last Modified time: 2019-11-28 18:19:53
*/ */
const Service = require("egg").Service; const Service = require("egg").Service;
...@@ -30,7 +30,8 @@ class UserService extends Service { ...@@ -30,7 +30,8 @@ class UserService extends Service {
TUserCityAverageDriveMonth, TUserCityAverageDriveMonth,
TUserCityJourneyDaily, TUserCityJourneyDaily,
TUserSummary, TUserSummary,
TProvince TProvince,
TCity
} = this.app.model; } = this.app.model;
this.MCityActive = TUserCityActiveDaily; this.MCityActive = TUserCityActiveDaily;
this.MCityIncreased = TUserCityIncreasedDaily; this.MCityIncreased = TUserCityIncreasedDaily;
...@@ -44,6 +45,7 @@ class UserService extends Service { ...@@ -44,6 +45,7 @@ class UserService extends Service {
this.MCityJourney = TUserCityJourneyDaily; this.MCityJourney = TUserCityJourneyDaily;
this.MUserSummary = TUserSummary; this.MUserSummary = TUserSummary;
this.MProvice = TProvince; this.MProvice = TProvince;
this.MCity = TCity;
} }
/** /**
...@@ -54,6 +56,14 @@ class UserService extends Service { ...@@ -54,6 +56,14 @@ class UserService extends Service {
foreignKey: "prov_code", foreignKey: "prov_code",
targetKey: "prov_code" targetKey: "prov_code"
}); });
this.MUserCity.belongsTo(this.MCity, {
foreignKey: "city_code",
targetKey: "city_code"
});
this.MUserCity.belongsTo(this.MCityRenew, {
foreignKey: "city_code",
targetKey: "city_code"
});
} }
/** /**
...@@ -72,8 +82,8 @@ class UserService extends Service { ...@@ -72,8 +82,8 @@ class UserService extends Service {
* @return {Promise.<boolean>} * @return {Promise.<boolean>}
* @Description 近N天 新增用户数 * @Description 近N天 新增用户数
*/ */
async last_n_day_user_increased(pid, n) { async last_n_day_user_increased({pid,cid,n}) {
const option = this.helper.seqOption({ n, pid }); const option = this.helper.seqOption({ n, pid,cid });
const data = await this.MCityIncreased.sum("total", option); const data = await this.MCityIncreased.sum("total", option);
return data; return data;
} }
...@@ -96,8 +106,8 @@ class UserService extends Service { ...@@ -96,8 +106,8 @@ class UserService extends Service {
* @return {Promise.<boolean>} * @return {Promise.<boolean>}
* @Description 近N天 用户活跃度 * @Description 近N天 用户活跃度
*/ */
async last_n_day_user_lively(pid, n) { async last_n_day_user_lively({pid,cid,n}) {
const option = this.helper.seqOption({ n, pid }); const option = this.helper.seqOption({pid,cid,n});
const data = await this.MCityActive.sum("total", option); const data = await this.MCityActive.sum("total", option);
return data; return data;
} }
...@@ -224,7 +234,7 @@ class UserService extends Service { ...@@ -224,7 +234,7 @@ class UserService extends Service {
* @param field {String} * @param field {String}
* @param value {String} * @param value {String}
* @return {Promise.<boolean>} * @return {Promise.<boolean>}
* @Description 获取某天用户总数 * @Description 获取某生某天用户总数 不传pid 统计所有
*/ */
async user_summary_provice_by_day(beginDate, endDate, pid) { async user_summary_provice_by_day(beginDate, endDate, pid) {
const { app, helper, MProvice, MUserCity } = this; const { app, helper, MProvice, MUserCity } = this;
...@@ -239,6 +249,32 @@ class UserService extends Service { ...@@ -239,6 +249,32 @@ class UserService extends Service {
], ],
group: ["prov_code", "day"], group: ["prov_code", "day"],
include: { model: MProvice, attributes: [] }, include: { model: MProvice, attributes: [] },
rollup:true,
raw: true
});
const data = await MUserCity.findAll(option);
return data;
}
/**
* @param field {String}
* @param value {String}
* @return {Promise.<boolean>}
* @Description 获取某天城市用户总数列表
*/
async user_summary_city_by_day({beginDate, endDate, pid, cid}) {
const { app, helper, MUserCity, MCity, MProvice, MCityRenew } = this;
const { col } = app.Sequelize;
var option = helper.seqOption({ beginDate, endDate, pid, cid });
Object.assign(option, {
attributes: [
"city_code",
'prov_code',
"total",
[col("t_user_city_renew_daily.total"),'renew'],
col("t_city.city_name"),
col("t_province.prov_name")
],
include: [{ model: MCity, attributes: [] },{ model: MProvice, attributes: []},{ model: MCityRenew, attributes: []}],
raw: true raw: true
}); });
const data = await MUserCity.findAll(option); const data = await MUserCity.findAll(option);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!