Commit 05572363 by liimin

完善接口

1 parent 580b0fec
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-21 11:20:01
* @Last Modified by: limin
* @Last Modified time: 2019-11-21 17:12:45
* @Last Modified time: 2019-12-04 15:53:54
*/
"use strict";
......@@ -27,9 +27,7 @@ class BaseController extends Controller {
* @Description 获取所有省份
*/
async provinces() {
const data = await this.CacheService.get("gds_provinces", () =>
this.BaseService.provinces()
);
const data = await this.BaseService.provinces();
this.ctx.body = this.ServerResponse.Success({ data });
}
/**
......@@ -43,9 +41,7 @@ class BaseController extends Controller {
this.ctx.body = this.ServerResponse.Error(null,this.ServerResponseCode.ILLEGAL_ARGUMENT);
return
}
const data = await this.CacheService.get(`gds_cities_${nPid}`, () =>
this.BaseService.cities_by_pid(nPid)
);
const data = await this.BaseService.cities_by_pid(nPid)
this.ctx.body = this.ServerResponse.Success(data);
}
}
......
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-21 11:20:01
* @Last Modified by: limin
* @Last Modified time: 2019-12-03 16:52:07
* @Last Modified time: 2019-12-04 17:59:15
*/
"use strict";
......@@ -25,48 +25,82 @@ class UserController extends Controller {
this.ServerResponse = ctx.response.ServerResponse;
}
/**
* 从内存获取日期(昨天,今天)
*/
async _fetch_date_in_cache(){
const { DATES } = this.helper.constant;
return await this.CacheService.get(DATES);
}
/**
* 内部方法 从内存获取 昨天的统计数据
* 比较数据时间 如果不是昨天的数据 则启动定时任务 更新一遍数据 再次获取数据并返回
* 对比和获取内存中的数据(总共30天,每天通过定时任务更新)
* 如果获取的时候数据还是最新则手动触发定时任务更新一次
*/
async _fetch_summary( { beginDate,endDate,isGetLast } ){
async _compare_get(){
const { USER_SUMMARY_30_DAY } = this.helper.constant;
var summary_30_day = await this.CacheService.get(USER_SUMMARY_30_DAY);
const { date } = summary_30_day;
const { yesterday } = await this._fetch_date_in_cache();
if(date !== yesterday){ //如果 内存中的数据的日期不是昨天的 则手动启动定时器 更新缓存数据
var { date } = summary_30_day;
var { yesterday } = await this._fetch_date_in_cache();
if(!this.helper.moment(date).isSame(yesterday)){ //如果 内存中的数据的日期不是昨天的 则手动启动定时器 更新缓存数据
await this.app.runSchedule('update_cache');
summary_30_day = await this.CacheService.get(USER_SUMMARY_30_DAY);
}
return summary_30_day
}
/**
* 内部方法 从内存获取 昨天的统计数据
* 比较数据时间 如果不是昨天的数据 则启动定时任务 更新一遍数据 再次获取数据并返回
*/
async _fetch_summary( { beginDate,endDate,isGetLast }, fn ){
var summary_30_day= await this._compare_get();
const { moment } =this.helper
var result=[];
if(isGetLast){
result = summary_30_day[date];
fn && fn(date,summary_30_day[date])
}else if(beginDate){
beginDate = beginDate.replaceAll('-','');
endDate = endDate ? endDate.replaceAll('-','') : beginDate;
if( beginDate === endDate ){
endDate = endDate || beginDate;
if(moment(beginDate).isSame(endDate) ){
result.push(summary_30_day[beginDate])
fn && fn(beginDate,summary_30_day[beginDate])
}else{
for(const day in summary_30_day){
if(day >= +beginDate && day <= +endDate ){
if(day ==='date') continue;
if(moment(day).isBetween(beginDate,endDate)
|| moment(day).isSame(beginDate)
|| moment(day).isSame(endDate)){
result.push(summary_30_day[day])
fn && fn(day,summary_30_day[day])
}
}
}
}else{
delete summary_30_day.date
if(fn){
for(const day in summary_30_day){
fn(day,summary_30_day[day])
}
}
result = Object.values(summary_30_day)
}
return result
}
/**
* 内部帮助方法
* @param {*} obj
* @param {*} field
*/
_reduce(obj,field){
return obj.reduce((pre,next)=>pre + +next[field],0)
}
/**
* 内部帮助方法
* @param {*} field
* @param {*} fn
*/
async _set(field,fn){
var total;
if(typeof field ==='string'){
......@@ -96,6 +130,7 @@ class UserController extends Controller {
return total;
}
/**
* 内部方法 从内存获取 范围时间内的数据
*/
......@@ -104,19 +139,53 @@ class UserController extends Controller {
const _list = await this._fetch_summary({ beginDate, endDate });
if( _list && _list.length ){
var fn = null;
var num=0;
if (pid) {
if(cid){
fn = async f=>_list.reduce((pre,next)=>pre+next['p'][pid]['c'][cid][f],0)
fn = async f=>_list.reduce((pre,next)=>{
num = next && next['p'][pid] && next['p'][pid]['c'][cid]?next['p'][pid]['c'][cid][f]:0
return pre + num
},0)
}else{
fn = async f=>_list.reduce((pre,next)=>pre+next['p'][pid][f],0)
fn = async f=>_list.reduce((pre,next)=>{
num = next && next['p'][pid] ? next['p'][pid][f] :0
return pre + num
},0)
}
}else{
fn = async f=>_list.reduce((pre,next)=>pre+next[f],0)
fn = async f=>_list.reduce((pre,next)=>{
num = next ? next[f] :0
return pre+num
},0)
}
res = await this._set(field,fn)
}
return res;
}
/**
* 内部方法 从内存获取 范围时间内的数据
*/
async _fetch_detail_by_range({ pid, cid , field, beginDate,endDate } ){
var res = []
var _set = this._set
var data = null
await this._fetch_summary({ beginDate, endDate },async (day,value)=>{
var fn = null;
if (pid) {
if(cid){
fn = async f=> value && value['p'][pid] && value['p'][pid]['c'][cid]?value['p'][pid]['c'][cid][f]:0
}else{
fn = async f=>value && value['p'][pid] ? value['p'][pid][f]:0
}
}else{
fn = async f=>value ? value[f]:0
}
data = await _set(field,fn);
res.push({ day, data })
});
return res;
}
/**
* @Router GET /screen/user/total
* @Description 数据大屏-用户总数统计.----参数pid 有 则返回对应的省份数据.没有则是全国数据的统计
......@@ -151,8 +220,6 @@ class UserController extends Controller {
// 昨天的付费转化率 (昨天的付费总人数 / 昨天用户总数)
const renew = this.helper.percent(r,u);
const data = { increased7, live7,increased30,live30,renew };
const aa= await this.UserService.user_gender({ pid,cid })
console.log(aa);
this.ctx.body = this.ServerResponse.Success(data);
}
......@@ -202,6 +269,30 @@ class UserController extends Controller {
this.ctx.body = this.ServerResponse.Success(data);
}
/**
* @Router GET /screen/user/trend
* @Description 数据大屏-1 用户新增趋势 2.用户活跃趋势, 3.用户付费趋势 4.用户车辆出行趋势
* @Request query integer pid 省份id
* @Request query integer cid 城市id
* @Request query string type 趋势类别 u:用户总数 i: 用户新增趋势 a: 用户活跃趋势, r:用户付费趋势 j:用户车辆出行趋势(默认:['u','i','a','r','j'] 所有)
* @Request query integer n 近N天数据 默认 30天
* @Request query string beginDate 查询开始时间 (2019-12-12)
* @Request query string endDate 查询结束时间 (2019-12-12)
*/
async trend({ query: { pid, cid, type, n = 30, beginDate , endDate } }) {
if(n){
if(n===30){
beginDate = endDate = null;
}else{
beginDate = this.helper.date(-n);
var { yesterday:endDate } = await this._fetch_date_in_cache();
}
}
type =type?(type.includes(',')?type.split(','):type):['u','i','a','r','j'];
const data = await this._fetch_detail_by_range( { pid, cid, field:type,beginDate, endDate } )
this.ctx.body = this.ServerResponse.Success(data);
}
}
module.exports = UserController;
......@@ -2,34 +2,34 @@
* @Author: limin
* @Date: 2019-11-21 11:19:43
* @Last Modified by: limin
* @Last Modified time: 2019-12-03 16:11:52
* @Last Modified time: 2019-12-04 17:28:07
*/
const moment = require("moment");
const constant = require("../common/constant");
exports.moment = moment;
/*
* string.replaceAll()---字符替换所有指定字符
* @parameter: FindText--原文本要替换值
* @parameter: RepText--将要替换值
* string.replace_all()---字符替换所有指定字符
* @parameter: from--原文本要替换值
* @parameter: to--将要替换值
*/
String.prototype.replaceAll = function (from, to) {
String.prototype.replace_all = function (from, to) {
var regExp = new RegExp(from, "g");
return this.replace(regExp, to);
}
// exports.relativeTime = time => moment(new Date(time * 1000)).fromNow();
exports.date = (n, f = "YYYY-MM-DD") => moment().add(n, "days").format(f);
exports.date = (n, f = "YYYY-MM-DD") =>
moment()
.add(n, "days")
.format(f);
exports.format_date = (date, f = "YYYY-MM-DD") =>moment(date+'').format(f);
/**
* 结束日期格式化函数
*/
exports.formatEndDate = end => `${end} 23:59:59`;
exports.format_end_date = end => `${end} 23:59:59`;
/**
* 字符串转json 如果是json字符串 返回json对象 如果不是JSON字符串 返回原始字符串
*/
exports.jsonParser = str => {
exports.json_parser = str => {
var res;
try {
res = JSON.parse(str);
......@@ -41,7 +41,7 @@ exports.jsonParser = str => {
/**
* json对象转字符串
*/
exports.jsonStringify = obj => {
exports.json_stringify = obj => {
var res;
if (typeof obj === "string") {
return obj;
......@@ -62,7 +62,7 @@ exports.percent = (num, total, fixed = 2) =>
/**
* 简单封装 sequelize 查询参数
*/
exports.seqOption = function({
exports.seq_option = function({
pid,
cid,
n,
......@@ -85,19 +85,19 @@ exports.seqOption = function({
} else if (n) {
// 查询近N天的数据 不包括今天
where.day = {
[between]: [this.date(n), this.formatEndDate(this.date(-1))]
[between]: [this.date(n), this.format_end_date(this.date(-1))]
};
} else if (n === 0) {
// 查询
where.day = {
[between]: [this.date(0), this.formatEndDate(this.date(0))]
[between]: [this.date(0), this.format_end_date(this.date(0))]
};
} else if (beginDate) {
if (!endDate) {
endDate = beginDate;
}
if (!endDate.includes(":")) {
endDate = this.formatEndDate(endDate);
endDate = this.format_end_date(endDate);
}
where.day = {
[between]: [beginDate, endDate]
......
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-21 11:18:45
* @Last Modified by: limin
* @Last Modified time: 2019-12-03 16:52:27
* @Last Modified time: 2019-12-04 14:50:35
*/
module.exports = app => {
......@@ -12,4 +12,5 @@ module.exports = app => {
app.router.get('/screen/user/city_range', app.controller.screen.user.city_range);
app.router.get('/screen/user/car_brand_range', app.controller.screen.user.car_brand_range);
app.router.get('/screen/user/drive_range', app.controller.screen.user.drive_range);
app.router.get('/screen/user/trend', app.controller.screen.user.trend);
};
\ No newline at end of file
......@@ -31,7 +31,7 @@ class UpdateCache extends Subscription {
_group(cities, f) {
const data = {
date:'20000101',
date:'2000-01-01',
};
function __push(target,obj){
target =target || {}
......@@ -57,9 +57,9 @@ class UpdateCache extends Subscription {
};
cities.forEach(function (city) {
const prov_code = f(city);
let { city_code,city_name,prov_name,total_user:u,renew:r,active:a,increase:i,journey:j,miles:m,online_time:o,day } = city
day = day.replaceAll('-','');
data.date=Math.max(data.date,day)
let { city_code,total_user:u,renew:r,active:a,increase:i,journey:j,miles:m,online_time:o,day } = city
// day = day.replace_all('-','');
data.date=this.helper.moment(day).isAfter(data.date)?day:data.date
if(!data[day]){
data[day] = {
p:{} //省 province
......@@ -76,10 +76,18 @@ class UpdateCache extends Subscription {
data[day]['p'][prov_code]['c']={}
}
data[day]['p'][prov_code]['c'][city_code]={ u,r,a,i,j,m,o };
});
}.bind(this));
return data
}
// task_total_country_cache(){
// const gender = await this.UserService.user_gender({});
// const city_range = await this.UserService.city_range( { limit:5 });
// const car_brand_range = await this.UserService.car_brand_range( { limit:6 })
// const drive_range = await this.UserService.drive_range( { })
// return { gender,city_range,car_brand_range,drive_range }
// }
// subscribe 是真正定时任务执行时被运行的函数
async subscribe() {
this.logger.info( "===============执行日常任务-缓存每日统计数据(总30天) begin==================");
......@@ -96,7 +104,7 @@ class UpdateCache extends Subscription {
value,
2 * 24 * 60 * 60 //两天过期
);
this.logger.info("user_summary_%s:%s",data.date,value);
this.logger.info("user_summary_%s([%s]):%s",data.date,Object.keys(data).join(','),value);
}else{
this.logger.warn("warnning=============user_summary_30_day===========is empty!");
}
......
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-21 14:32:51
* @Last Modified by: limin
* @Last Modified time: 2019-11-29 09:47:18
* @Last Modified time: 2019-12-04 11:12:10
*/
"use strict";
......@@ -19,20 +19,26 @@ class CacheService extends Service {
this.PREFIX = ctx.helper.constant.PREFIX;
}
async set(key, value, ex = 60 * 60) {
this.app.redis && (await this.app.redis.set(`${this.PREFIX}${key}`, this.helper.jsonStringify(value), "EX", ex));
this.app.redis && (await this.app.redis.set(`${this.PREFIX}${key}`, this.helper.json_stringify(value), "EX", ex));
}
async get(key, fnGetFromDB, ex) {
if (this.app.redis) {
var value = await this.app.redis.get(`${this.helper.constant.PREFIX}${key}`);
if(value){
value =this.helper.jsonParser(value)
value =this.helper.json_parser(value)
return value
}
}
if (fnGetFromDB) {
var data = await fnGetFromDB();
await this.set(key, data, ex);
if( data && data.length ){
const{ date } =data[0]
const { today } = await this.get(this.helper.constant.DATES)
if(date.split(' ')[0] === today) {
await this.set(key, data, ex);
}
}
return data;
}
return null;
......
......@@ -2,7 +2,7 @@
* @Author: limin
* @Date: 2019-11-21 11:18:37
* @Last Modified by: limin
* @Last Modified time: 2019-12-03 17:06:34
* @Last Modified time: 2019-12-04 10:59:19
*/
const Service = require("egg").Service;
......@@ -67,7 +67,7 @@ class UserService extends Service {
async city_range({ pid, limit }) {
const { app, helper, MCity, MUserDaily } = this;
const { col } = app.Sequelize;
const option = helper.seqOption({
const option = helper.seq_option({
pid,
limit,
order: [["total_user", "DESC"]]
......@@ -76,7 +76,8 @@ class UserService extends Service {
Object.assign(option, {
attributes: [
col("total_user",'total'),
col("t_city.city_name",'city')
col("t_city.city_name",'city'),
col("update_time",'date')
],
include: { model: MCity, attributes: [] },
raw: true
......@@ -94,7 +95,7 @@ class UserService extends Service {
async car_brand_range({ pid, cid, limit }) {
const { app, helper, MUserCarBrand } = this;
const { fn, col } = app.Sequelize;
const option = helper.seqOption({
const option = helper.seq_option({
pid,
cid,
limit,
......@@ -104,6 +105,7 @@ class UserService extends Service {
attributes: [
col("brand_name",'brand'),
[fn("SUM", col("brand_cars")), "total"],
col("update_time",'date')
],
group:'brand_name',
raw: true
......@@ -120,7 +122,7 @@ class UserService extends Service {
*/
async drive_range({ pid, cid }) {
const { app, helper, MUserDriveInfo } = this;
const option = helper.seqOption({ pid, cid });
const option = helper.seq_option({ pid, cid });
const { fn, col } = app.Sequelize;
Object.assign(option, {
attributes: [
......@@ -138,7 +140,8 @@ class UserService extends Service {
[fn("SUM", col("w_10_20")),'w_10_20'],
[fn("SUM", col("w_20_30")),'w_20_30'],
[fn("SUM", col("w_30_50")),'w_30_50'],
[fn("SUM", col("w_50_")),'w_50_']
[fn("SUM", col("w_50_")),'w_50_'],
col("update_time",'date')
],
raw: true
});
......@@ -155,7 +158,7 @@ class UserService extends Service {
async user_summary_city_by_day({beginDate, endDate, pid, cid}) {
const { app, helper, MUserDaily: MUserCity, MCity, MProvice } = this;
const { col } = app.Sequelize;
var option = helper.seqOption({ beginDate, endDate, pid, cid });
var option = helper.seq_option({ beginDate, endDate, pid, cid });
Object.assign(option, {
attributes: [
"city_code",
......@@ -187,7 +190,7 @@ class UserService extends Service {
async user_realtime({pid, cid}) {
const { app, helper, MUserRealTime, MCity, MProvice } = this;
const { col } = app.Sequelize;
var option = helper.seqOption({ pid, cid });
var option = helper.seq_option({ pid, cid });
Object.assign(option, {
attributes: [
"city_code",
......@@ -215,14 +218,15 @@ class UserService extends Service {
*/
async user_gender({pid, cid}) {
const { app, helper, MUserGender } = this;
var option = helper.seqOption({ pid, cid });
var option = helper.seq_option({ pid, cid });
const { fn, col } = app.Sequelize;
Object.assign(option, {
attributes: [
'gender_range',
[fn("SUM", col("total")), "total"],
[fn("SUM", col("male")), "male"],
[fn("SUM", col("female")), "female"]
[fn("SUM", col("female")), "female"],
col("update_time",'date')
],
group:'gender_range',
raw: true
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!