Commit 9a2f01f2 authored by 王波's avatar 王波

Merge branch 'c_server_ts_perf' into c_server_ts_cultivate

* c_server_ts_perf:
  feat: 🎸 删除complieServer
  fix: 🐛 格式错误
  异步编译支持
  fix: 🐛 bug
  sellerId编译
  编译constants appId
  services添加默认值
  排行榜开奖
  save
  忽略登录
  排行榜开奖

# Conflicts:
#	v2.0/compileServer/config.json
parents 24566176 02308ab5
......@@ -3,3 +3,4 @@
.vscode
debug.log
node_modules
dist/
\ No newline at end of file
/** @format */
const fs = require('fs-extra')
const config = require('./config.json')
const { getDecorators, getPreChecks, getPreUpdates } = require('./utils/formatConfg')
const serverTemplatePath = 'templates'
const controllerImport = (controller = {}) => {
const result = {
services: {}
}
for (let fn in controller) {
for (let main of controller[fn].main) {
if (!result.services[main.type]) {
result.services[main.type] = {}
}
result.services[main.type][main.service] = true
}
}
return result
}
const customFileMap = (controllers = {}) => {
const result = {
decorators: {},
utils: {},
services: {}
}
for (let controllerType in controllers) {
for (let controller in controllers[controllerType]) {
for (let fn in controllers[controllerType][controller]) {
for (let decorator of controllers[controllerType][controller][fn].decorators) {
if (decorator.type === 'custom') {
result.decorators[decorator.name] = true
}
for (let util of decorator.params || []) {
if (util.type && util.type === 'custom') {
result.utils[util.name] = true
}
}
}
for (let main of controllers[controllerType][controller][fn].main) {
if (main.type === 'custom') {
if (!result.services[main.service]) {
result.services[main.service] = {}
}
result.services[main.service][main.function] = main.params
}
}
}
}
}
return result
}
const run = async (gulp, nunjucksRender, rename, nunjucksRenderConfig) => {
//编译自定义文件
const { decorators, utils, services } = customFileMap(config.controllers)
for (let decorator in decorators) {
await gulp
.src(`${serverTemplatePath}/decorator.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: decorator
}
})
)
.pipe(rename(`${decorator}.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/decorator/custom'))
}
await gulp
.src(`${serverTemplatePath}/decorator.export.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
decorators
}
})
)
.pipe(rename(`index.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/decorator/custom'))
for (let util in utils) {
await gulp
.src(`${serverTemplatePath}/util.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: util
}
})
)
.pipe(rename(`${util}.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/utils/custom'))
}
await gulp
.src(`${serverTemplatePath}/util.export.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
utils
}
})
)
.pipe(rename(`index.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/utils/custom'))
for (let service in services) {
await gulp
.src(`${serverTemplatePath}/service.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: service,
fns: services[service]
}
})
)
.pipe(rename(`${service}.service.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/service/custom'))
}
await gulp
.src(`${serverTemplatePath}/service.export.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
services
}
})
)
.pipe(rename(`index.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/service/custom'))
//编译controller.common
for (let commonController in config.controllers.common) {
const controller = config.controllers.common[commonController]
await gulp
.src(`${serverTemplatePath}/controller.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: commonController,
model: controller,
...controllerImport(controller),
commmonDecorators: getDecorators(controller, 'common'),
customDecorators: getDecorators(controller, 'custom'),
commonPreChecks: getPreChecks(controller, 'common'),
customPreChecks: getPreChecks(controller, 'custom'),
commonPreUpdates: getPreUpdates(controller, 'common'),
customPreUpdates: getPreUpdates(controller, 'custom')
}
})
)
.pipe(rename(`${commonController}.controller.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/controller/common'))
}
//编译controller.custom
for (let customController in config.controllers.custom) {
const controller = config.controllers.custom[customController]
await gulp
.src(`${serverTemplatePath}/controller.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
name: customController,
model: controller,
...controllerImport(controller),
commmonDecorators: getDecorators(controller, 'common'),
customDecorators: getDecorators(controller, 'custom'),
commonPreChecks: getPreChecks(controller, 'common'),
customPreChecks: getPreChecks(controller, 'custom'),
commonPreUpdates: getPreUpdates(controller, 'common'),
customPreUpdates: getPreUpdates(controller, 'custom')
}
})
)
.pipe(rename(`${customController}.controller.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/controller/custom'))
}
//接口导出
await gulp
.src(`${serverTemplatePath}/controller.export.njk`)
.pipe(
nunjucksRender({
...nunjucksRenderConfig,
data: {
controllers: config.controllers
}
})
)
.pipe(rename(`index.ts`))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath))
}
module.exports = {
run
}
/** @format */
const gulp = require('gulp')
const rename = require('gulp-rename')
const nunjucksRender = require('gulp-nunjucks-render')
const prettier = require('gulp-prettier')
const codeGenerate = require('./generate')
var jsScript = 'node'
if (process.env.npm_config_argv !== undefined && process.env.npm_config_argv.indexOf('debug') > 0) {
jsScript = 'node debug'
}
const ServerFullPath = '../src'
const prettierConfig = {
printWidth: 120,
semi: false,
singleQuote: true,
trailingComma: 'none',
bracketSpacing: true,
arrowParens: 'avoid',
insertPragma: true,
tabWidth: 2,
useTabs: false
}
const nunjucksRenderConfig = {
path: 'templates',
ext: '.ts',
manageEnv: environment => {
environment.addFilter('firstToCapital', str => {
return str.charAt(0).toUpperCase() + str.slice(1)
})
environment.addFilter('groupByTypeAndService', value => {
const res = {}
for (let main of value) {
if (!res[main.type]) {
res[main.type] = {}
}
res[main.type][main.service] = true
}
return res
})
},
ServerFullPath
}
gulp.task('build', function () {
require('events').EventEmitter.defaultMaxListeners = 0
return codeGenerate.run(gulp, nunjucksRender, rename, nunjucksRenderConfig)
})
console.log(nunjucksRenderConfig.ServerFullPath + '/**/*.ts')
gulp.task('format', () => {
return gulp
.src(nunjucksRenderConfig.ServerFullPath + '/**/*.ts')
.pipe(prettier(prettierConfig))
.pipe(gulp.dest(nunjucksRenderConfig.ServerFullPath + '/'))
})
gulp.task('code', gulp.series('build', 'format'))
{
"name": "nunjucks-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"complile": "gulp code"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@typescript-eslint/parser": "^4.8.1",
"eslint": "^7.13.0",
"gulp": "^4.0.2",
"gulp-nunjucks-render": "^2.2.3",
"gulp-prettier": "^3.0.0",
"gulp-rename": "^2.0.0",
"typescript": "^4.0.5"
},
"dependencies": {
"fs-extra": "^9.0.1"
}
}
/** @format */
{%- for type, type_item in controllers -%}
{%- for controller, controller_item in type_item %}
import {{type | capitalize}}{{controller | capitalize}}Controller from './controller/{{type}}/{{controller}}.controller'
const {{type | capitalize}}{{controller | capitalize}}ControllerInstance = new {{type | capitalize}}{{controller | capitalize}}Controller()
{%- endfor -%}
{%- endfor %}
export default {
{%- for type, type_item in controllers -%}
{%- for controller, controller_item in type_item -%}
{%- for function, fucntion_item in controller_item %}
{{function}}: {{type | capitalize}}{{controller | capitalize}}ControllerInstance.{{function}}
{%-if loop.last-%}{%else%},{%-endif-%}
{%- endfor -%}
{%-if loop.last-%}{%else%},{%-endif-%}
{%- endfor -%}
{%-if loop.last-%}{%else%},{%-endif-%}
{%- endfor %}
}
/** @format */
{% import "macro.njk" as macro -%}
import { {{ commmonDecorators }} } from '../../decorator/common'
{%if commonPreChecks and commonPreChecks.length -%}
import { {{commonPreChecks}} } from '../../utils/common/check'
{% endif -%}
{%if commonPreUpdates and commonPreUpdates.length -%}
import { {{commonPreUpdates}} } from '../../utils/common/update'
{% endif -%}
{%if customDecorators.length -%}
import { {{customDecorators}} } from '../../decorator/custom'
{% endif -%}
import customUtil from '../../utils/custom'
import { resultsModel } from '../../sdk'
{{macro.genControllerService(services)}}
{# import commonService from '../../service/common'
import customService from '../../service/custom' #}
export default class {{name | capitalize}}Controller {
{%- for fn, item in model %}
/**
* {{item.desc}}
*/
{{-macro.genDecorator(model[fn].decorators)}}
@services([{{-macro.genServicesDecorator(model[fn].main)}}])
{{-macro.genPreDecorator(model[fn].decorators)}}
async {{fn}}(
context: IContext<IParams>,
{ activityInfo, userInfo{{-macro.genRegisteInfosParams(model[fn].decorators)}} }: IControllerInfos,
{{-macro.genServicesParams(model[fn].main)-}},
{{-macro.genPreCheckDataParams(model[fn].decorators)-}}
) {
{{-macro.genMain(model[fn].main)}}
{{-macro.genReturn(model[fn].main)}}
}
{%- endfor %}
}
/** @format */
{%for decorator, decorator_item in decorators-%}
import {{decorator}} from './{{decorator}}'
{%-endfor%}
const custom = {
{%-for decorator, decorator_item in decorators%}
{{decorator}}{%if loop.last%}{%else%},{%endif%}
{%-endfor%}
}
export default custom
export {
{%-for decorator, decorator_item in decorators%}
{{decorator}}{%if loop.last%}{%else%},{%endif%}
{%-endfor%}
}
/** @format */
import { resultsModel } from '../../sdk'
import { CODE_TYPES } from '../../constants'
export default function {{name}}(params) {
return function (target: Object, name: string, descriptor: PropertyDescriptor) {
const method = descriptor.value
descriptor.value = function (...args: any[]) {
const [context, otherArgs = {}] = args
return method.apply(target, [context, { ...otherArgs }])
}
}
}
{# 生成控制器引用的服务 #}
{% macro genControllerService(services)%}
{%- for type, type_item in services -%}
import { {%for service, service_item in type_item %}{{type|capitalize}}{{service|capitalize}}Service{%- if loop.last %}{% else %}, {% endif %}{% endfor %} } from '../../service/{{type}}'
{% endfor%}
{% endmacro %}
{# 生成装饰器 #}
{% macro genDecorator(decorators) %}
{%- for decorator in decorators %}
{%- if decorator.name != 'preCheck' and decorator.name != 'preUpdate' %}
@{{ decorator.name }}
{%- if decorator.name == 'noCatch' or decorator.name == 'noCheckUser' -%}
{%- else -%}
([{%- for param in decorator.params -%}'{{ param }}'{%- if loop.last %}{% else %}, {% endif %}{%- endfor -%}])
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{% endmacro %}
{# 生成装饰器 #}
{% macro genPreDecorator(decorators) %}
{%- for decorator in decorators %}
{%- if decorator.name == 'preCheck' or decorator.name == 'preUpdate' %}
@{{ decorator.name }}([{%- for param in decorator.params -%}{{param.name}}{%- if param.params %}({%- for utilParam in param.params -%}{{utilParam}}{%- if loop.last %}{% else %}, {% endif %}{%- endfor -%}){% endif %}{%- if loop.last %}{% else %}, {% endif %}{%- endfor -%}])
{%- endif -%}
{%- endfor -%}
{% endmacro %}
{# 生成services装饰器 #}
{% macro genServicesDecorator(mains) %}
{%- for type, type_item in mains | groupByTypeAndService -%}
{%- for service, service_item in type_item -%}
{{type|capitalize}}{{service|capitalize}}Service{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{%- endmacro %}
{# 生成services参数 #}
{% macro genServicesParams(mains) %}
[
{%- for type, type_item in mains | groupByTypeAndService -%}
{%- for service, service_item in type_item -%}
{{ type }}{{service | capitalize}}Service{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
]: [
{%- for type, type_item in mains | groupByTypeAndService -%}
{%- for service, service_item in type_item -%}
{{type|capitalize}}{{service|capitalize}}Service{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
]
{%- endmacro %}
{# 生成注入参数 #}
{% macro genRegisteInfosParams(decorators) %}
{%- for decorator in decorators -%}
{% if decorator.type == 'common' and decorator.name == 'registeInfos' %}
{%- for param in decorator.params -%}
{%- if loop.first %}, {% else %}{% endif %}{{ param }}{%- if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
{% endif %}
{%- endfor -%}
{%- endmacro %}
{# 生成common preCheck返回数据 #}
{% macro genPreCheckDataParams(decorators) %}
{% set preChecks = {'checkInviteId':'inviteUserInfo','checkValidObjectPrize':'awardInfo','checkValidEnamePrize':'awardInfo', 'checkJoinId': 'joinInfo'} -%}
{%- set preCheckData = [] -%}
{% for decorator in decorators -%}
{%- if decorator.type == 'common' and decorator.name== 'preCheck' -%}
{%- for param in decorator.params -%}
{%- for key, data in preChecks -%}
{%- if key === param.name%} {% set preCheckData = preCheckData.concat(data)%} {% endif %}
{%- endfor -%}
{%- endfor -%}
{%- endif -%}
{%- endfor -%}
{%- if preCheckData.length -%}
{ {{preCheckData | join(',')}} }: IPreCheckData
{% endif %}
{%- endmacro %}
{# 生成函数体 #}
{% macro genMain(mains) %}
{%- for main in mains %}
const {{main.type}}{{main.service|capitalize}}{{main.function|firstToCapital}}Result{{loop.index}} = await {{main.type}}{{main.service | capitalize}}Service.{{main.function}}(
{%- for param in main.params -%}
{% if param.type == 'var' %}{{param.value}}{% else %}'{{param.value}}'{% endif %}{% if loop.last %}{% else %}, {% endif %}
{%- endfor -%}
)
{%- endfor -%}
{%- endmacro %}
{# 生成return结果 #}
{% macro genReturn(mains) %}
return resultsModel.success({
{%- for main in mains -%}
{% if main.return %}
...{{main.type}}{{main.service|capitalize}}{{main.function|firstToCapital}}Result{{loop.index}}{% if loop.last %}{% else %},{% endif %}
{%- endif -%}
{%- endfor %}
})
{%- endmacro%}
\ No newline at end of file
/** @format */
{%- for service, service_item in services %}
import Custom{{ service | capitalize }}Service from './{{ service }}.service'
{%- endfor %}
const custom = {
{%- for service, service_item in services %}
Custom{{ service | capitalize }}Service{% if loop.last %}{%else%},{% endif %}
{%- endfor %}
}
export default custom
export {
{%- for service, service_item in services %}
Custom{{ service | capitalize }}Service{% if loop.last %}{%else%},{% endif %}
{%- endfor %}
}
/**
* 基本信息
*
* @format
*/
import { BaseDao, TBAPIS } from '../../sdk'
import { ACTIVITY_STATUS } from '../../constants'
import { getToday } from '../../utils'
export default class {{ name | capitalize }}Service {
context: IContext<IParams>
joindao: IBaseDao
constructor(context: IContext<IParams>) {
this.context = context
}
{% for fn, fn_item in fns -%}
async {{ fn }}({%- for param in fn_item -%}param{{loop.index}}{% if loop.last %}{% else %},{% endif %}{%- endfor -%}) {
const { openId, data } = this.context
return {}
}
{%- endfor %}
}
/** @format */
{%for util, util_item in utils-%}
import {{util}} from './{{util}}'
{%-endfor%}
const custom = {
{%-for util, util_item in utils%}
{{util}}{%if loop.last%}{%else%},{%endif%}
{%-endfor%}
}
export default custom
export {
{%-for util, util_item in utils%}
{{util}}{%if loop.last%}{%else%},{%endif%}
{%-endfor%}
}
/** @format */
import { resultsModel } from '../../sdk'
import { CODE_TYPES } from '../../errorCode'
export default async function {{name}}(context: IContext<IParams>, { activityInfo }: IControllerInfos) {
// TO DO
}
/** @format */
// 获取去重后的装饰器
function getDecorators(controller, decoratorType) {
let decorators = decoratorType === 'common' ? [{ type: 'common', name: 'services' }] : []
decorators = [...decorators, ...Object.values(controller).map(v => v.decorators)].flat()
return [...new Set(decorators.filter(v => v.type === (decoratorType || 'common')).map(v => v.name))]
}
function getPreChecks(controller, checkType) {
checkType = checkType || 'common'
let decorators = []
decorators = [...decorators, ...Object.values(controller).map(v => v.decorators)].flat()
const preChecks = [...decorators.filter(v => v.type === 'common' && v.name === 'preCheck').map(v => v.params)].flat()
return [...new Set(preChecks.filter(v => v.type === checkType && v.behave === 'check').map(v => v.name))]
}
function getPreUpdates(controller, updateType) {
updateType = updateType || 'common'
let decorators = []
decorators = [...decorators, ...Object.values(controller).map(v => v.decorators)].flat()
const preUpdates = [
...decorators.filter(v => v.type === 'common' && v.name === 'preUpdate').map(v => v.params)
].flat()
return [...new Set(preUpdates.filter(v => v.type === updateType && v.behave === 'update').map(v => v.name))]
}
module.exports = {
getDecorators,
getPreChecks,
getPreUpdates
}
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -19,7 +19,9 @@
"mock": "cd mockServer && npm start"
},
"config": {
"notNeedLogin": []
"notNeedLogin": [
"endOfActivityRewards"
]
},
"optionalDependencies": {
"@types/lodash": "^4.14.160",
......
......@@ -42,18 +42,19 @@ export const TAOBAO_SUCCESS_ORDER_STATUS: string[] = [
export const ACTIVITY_OPEN_PRIZE_STATUS = {
//开奖状态
AWAIT: 1,
FAIL: 2,
SUCCESS: 3
OPENING: 2,
SUCCESS: 3,
FAIL: 4
}
// 活动状态
export const enum ACTIVITY_STATUS {
export enum ACTIVITY_STATUS {
NORMAL = 1,
DELETE = 2
}
// 奖品状态
export const enum DELETE_STATUS {
export enum DELETE_STATUS {
NORMAL = 1,
DELETE = 2
}
......@@ -111,10 +112,10 @@ export enum STAT_TYPE {
// 每次参与消耗次数
export const JOIN_NEED_TIMES = 1
export const appId = '${需要补充}'
export const appId = '1234'
// 商铺id 拼接vip链接用
export const sellerId = '${商铺id}'
export const sellerId = '1234'
// C端的APP NAME
export const C_APP_NAME: string = `promotioncenter-${appId}`
/** @format */
import { services, checkParams, registeInfos } from '../decorator/common'
import { services, checkParams, registeInfos, noCheckUser } from '../decorator/common'
import { resultsModel } from '../sdk'
import { CommonAwardsService } from '../service/common'
import { CommonAwardsService, CommonBaseService } from '../service/common'
import preCheck from '../decorator/common/preCheck'
import {
checkActivityTime,
......@@ -10,6 +10,7 @@ import {
checkValidEnamePrize,
checkValidObjectPrize
} from '../utils/common/check/'
import { PRIZE_DATA_TYPE } from '../constants'
export interface IReceivePrizeControllerInfos extends IControllerInfos {
awardInfo: IAwards
......@@ -90,4 +91,27 @@ export default class AwardsController {
return resultsModel.success(drawResult)
}
/**
* 活动结束开奖
*/
@noCheckUser
@services([CommonBaseService, CommonAwardsService])
async endOfActivityRewards(
context: IContext<IParams>,
{},
[commonBaseService, commonAwardsService]: [CommonBaseService, CommonAwardsService]
) {
const activityList = await commonBaseService.getNeedRewardsActivityList()
const openResult = await commonAwardsService.openPrize(
activityList,
PRIZE_DATA_TYPE.RANKING,
'sortKey',
'sortTimeKey',
200
)
return resultsModel.success({
...openResult
})
}
}
/** @format */
import { services, checkParams, preCheck, registeInfos } from '../../decorator/common'
import { services, checkParams, preCheck, registeInfos, noCheckUser } from '../../decorator/common'
import {
checkPrizeExpired,
checkValidObjectPrize,
......@@ -8,7 +8,7 @@ import {
} from '../../utils/common/check'
import customUtil from '../../utils/custom'
import { resultsModel } from '../../sdk'
import { CommonAwardsService } from '../../service/common'
import { CommonAwardsService, CommonBaseService } from '../../service/common'
export default class AwardsController {
/**
......@@ -86,4 +86,26 @@ export default class AwardsController {
...commonAwardsDrawLotteryResult1
})
}
/**
* 排行榜开奖
*/
@noCheckUser
@services([CommonBaseService, CommonAwardsService])
async endOfActivityRewards(
context: IContext<IParams>,
{ activityInfo, userInfo }: IControllerInfos,
[commonBaseService, commonAwardsService]: [CommonBaseService, CommonAwardsService]
) {
const commonBaseGetNeedRewardsActivityListResult1 = await commonBaseService.getNeedRewardsActivityList()
const commonAwardsOpenPrizeResult2 = await commonAwardsService.openPrize(
commonBaseGetNeedRewardsActivityListResult1,
1,
'sortKey',
'sortTimeKey',
200
)
return resultsModel.success({
...commonAwardsOpenPrizeResult2
})
}
}
......@@ -31,7 +31,7 @@ async function formatBaseInfos(context: IContext<IParams>, baseInfos: ICheckCont
}
// 注入服务
export default function services(services: Constructor[]) {
export default function services(services: Constructor[] = []) {
return (target: Object, name: string, descriptor: PropertyDescriptor) => {
const method = descriptor.value
......
......@@ -33,6 +33,7 @@ export default {
receiveObjectPrize: CommonAwardsControllerInstance.receiveObjectPrize,
receiveEnamePrize: CommonAwardsControllerInstance.receiveEnamePrize,
drawLotteryPrize: CommonAwardsControllerInstance.drawLotteryPrize,
endOfActivityRewards: CommonAwardsControllerInstance.endOfActivityRewards,
getShareInfo: CommonShareControllerInstance.getShareInfo,
doHelp: CommonShareControllerInstance.doHelp,
testAddStat: CustomTest1ControllerInstance.testAddStat,
......
......@@ -13,7 +13,8 @@ import {
ACTIVITY_STATUS,
DELETE_STATUS,
SWICH_TOCK,
SHIP_STATUS
SHIP_STATUS,
ACTIVITY_OPEN_PRIZE_STATUS
} from '../../constants'
import { AWARDS_DB_NAME, PRIZE_CONFIG_DB_NAME } from '../../db'
import { sendTBAward, getSellerSession, rand, formatPrizeProbalityRange } from '../../utils'
......@@ -315,4 +316,74 @@ export default class AwardsService extends UserService {
}
)
}
/**
* 排行榜开奖
* @param activityInfo
* @param prizeDataType
* @param sortKey
* @param sortTimeKey
* @param limit
*/
async openPrize(activityList, prizeDataType, sortKey: string, sortTimeKey: string, limit?: number) {
const fail = []
const success = []
for (let activityInfo of activityList) {
const { _id } = activityInfo
await this.activitydao.update({ _id }, { $set: { openPrizeStatus: ACTIVITY_OPEN_PRIZE_STATUS.OPENING } })
const prizeConfigList = await this.getPrizeConfig({
activityId: _id,
prizeDataType
})
const userList = await this.userdao.find<IUserInfo>(
{
activityId: _id
},
{
sort: { [sortKey]: -1, [sortTimeKey]: 1 },
limit: limit || 100
}
)
const prizeList = []
prizeConfigList.forEach(prizeConfig => {
const { rank, _id: prizeId, type, name, image, credits } = prizeConfig
let [min, max] = rank.split('-')
if (!max) max = min
for (let i = +min - 1; i < +max + 1; i++) {
if (userList[i]) {
const { openId, userNick } = userList[i]
prizeList.push({
openId,
prizeId,
activityId: _id,
drawStatus: DRAW_STATUS.WAITAWARD,
prizeDataType,
remark: '',
credits: +credits,
type,
name,
image,
userNick,
createDay: getToday(),
shipStatus: type === PRIZE_TYPE.OBJECT ? SHIP_STATUS.NO_ADDRESS : '',
createTime: Date.now(),
updateTime: Date.now()
})
}
}
})
let result = null
if (prizeList.length) {
result = await this.awardsdao.insertMany(prizeList)
}
if (result) {
await this.activitydao.update({ _id }, { $set: { openPrizeStatus: ACTIVITY_OPEN_PRIZE_STATUS.SUCCESS } })
success.push(_id)
} else {
await this.activitydao.update({ _id }, { $set: { openPrizeStatus: ACTIVITY_OPEN_PRIZE_STATUS.FAIL } })
fail.push(_id)
}
}
return { success, fail }
}
}
......@@ -6,7 +6,7 @@
import { BaseDao, TBAPIS } from '../../sdk'
import { ACTIVITY_CONFIG_DB_NAME } from '../../db'
import { ACTIVITY_STATUS } from '../../constants'
import { ACTIVITY_OPEN_PRIZE_STATUS, ACTIVITY_STATUS } from '../../constants'
export default class BaseService {
context: IContext<any>
......@@ -52,4 +52,14 @@ export default class BaseService {
)
return { list }
}
/**
* 获取需要开奖的活动列表
*/
async getNeedRewardsActivityList() {
return await this.activitydao.find<IActivityInfo>({
endTime: { $lt: Date.now() },
openPrizeStatus: { $in: [ACTIVITY_OPEN_PRIZE_STATUS.AWAIT, ACTIVITY_OPEN_PRIZE_STATUS.FAIL] }
})
}
}
......@@ -37,17 +37,20 @@ export default class StatService {
* @memberof StatService
*/
async addStat(
type: number,
type: number | string,
userInfo: IUserInfo = {} as IUserInfo,
customStatData: object = {}
): Promise<{ id: string }> {
const { openId } = this.context
const { activityId } = this.context.data
const { userNick } = userInfo
const typeName = typeof type === 'string' ? type : STAT_TYPE[type];
const _type = typeof type === 'string' ? STAT_TYPE[type] : type;
const id = await this.statdao.insertOne({
activityId,
type,
typeName: STAT_TYPE[type],
type: _type,
typeName,
userNick,
openId,
...customStatData,
......
......@@ -20,7 +20,7 @@ interface ICommonActivityPrize {
properiodfrom?: number
lockStatus?: number
switchStock?: number
rank?: string | number
rank?: string
credits?: string | number
useUrl?: string
stock?: number
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment