wheel-surf.js
12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
const _ = require('lodash');
const aes = require('../../../utils/aes');
const logger = global.yoho.logger;
const _sender = global.yoho.sender;
const mysqlCli = global.yoho.utils.mysqlCli;
/**
* 上报
* @param type 0: packrain 1: turntable
* @param tags 一些基础参数
* @param fields 红包的金额
* @param isFail 接口是否失败
*/
const sendMessage = (type, tags, fields, isFail) => {
if (!_sender) {
return;
}
const hostname = (require('os').hostname());
let typeName = ['turntable-red', 'turntable-coupon'][type];
let initTags = {
hostname,
pid: process.pid || 0,
app: global.yoho.config.appName,
type: typeName
};
tags = Object.assign({}, initTags, tags);
isFail = isFail ? 1 : 0;
fields = Object.assign({}, fields);
let mesurement = ['monitor_success_report', 'monitor_error_report'][isFail];
try {
_sender.addMessage({
measurement: mesurement,
tags,
fields
});
} catch (e) {
logger.error(e);
}
};
const prizeType = {
1: '谢谢惠顾',
2: '红包',
3: '优惠券',
4: '实物奖品'
};
class ActWheelSurfModelRedis extends global.yoho.BaseModel {
constructor(ctx) {
super(ctx);
this.redis = global.yoho.redis;
this.client = this.redis.client;
}
async getNowConf(obj) {
try {
let data = {};
// 兼容线上活动
if (+obj.act_id !== 44) {
try {
obj.act_id = parseInt(aes.decryptUid(obj.act_id), 10);
} catch (err) {
obj.act_id = 0;
}
}
if (!obj.act_id) {
return {};
}
data.conf = await this.client.hgetallAsync(`turntable:${obj.act_id}`)
.then(conf => {
conf = conf || {};
Object.keys(conf).forEach(key => {
if (conf[key] && !_.isNaN(Number(conf[key]))) {
conf[key] = Number(conf[key])
}
});
return conf;
});
// 获取当前活动奖品
let prize = await this.client.lrangeAsync(`turntable:${obj.act_id}:prize`, 0, 7)
.then(prizes => {
return prizes.map(prize => {
return JSON.parse(prize);
})
});
data.prize = prize.length;
data.emptyPrize = {};
for (let value of prize) {
if (value.type === 1) {
data.emptyPrize = value;
break;
}
}
let idx = obj.act_id - 1;
let act = await this.client.lrangeAsync('turntable:activity', idx, idx).then(act => {
return JSON.parse(act[0] || {});
});
let nowDate = new Date();
nowDate = parseInt(nowDate.getTime() / 1000);
if (act.startTime > nowDate) {
data.startType = false;
data.errorType = 0;
data.errorMsg = '活动未开始';
}
if (act.endTime < nowDate) {
data.startType = false;
data.errorType = 1;
data.errorMsg = '活动已过期';
}
// 获取当去用户剩余次数
let residueCount;
// 判断用户是否登录 如果没登录就取当前活动最大次数
if (obj.uid) {
// 每日最大次数
if (data.conf.times_type === 1) {
// 获取当天0点和23:59:59
let startTime = new Date(new Date().toLocaleDateString()).getTime();
let endTime = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1).getTime();
let usedArr = await this.client.zrangebyscoreAsync(`turntable:${obj.act_id}:user:${obj.uid}:prize`, startTime, endTime);
if (usedArr.length > 100) {
await this.client.delAsync(`turntable:${obj.act_id}:user:${obj.uid}:prize`);
}
residueCount = data.conf.day_limit_times;
}
} else {
residueCount = 0;
}
data.residueCount = residueCount;
return Promise.resolve(data);
} catch (e) {
logger.error(e);
return Promise.reject({code: 305, result: false, msg: '服务错误,请稍等'});
}
}
async goPrize(obj) {
try {
// 校验有效活动时间
// 兼容线上活动
if (+obj.act_id !== 44) {
try {
obj.act_id = parseInt(aes.decryptUid(obj.act_id), 10);
} catch (err) {
obj.act_id = 0;
}
}
if (!obj.act_id) {
return {};
}
let idx = obj.act_id - 1;
let act = await this.client.lrangeAsync('turntable:activity', idx, idx).then(act => {
return JSON.parse(act[0] || {});
});
let nowDate = new Date();
nowDate = parseInt(nowDate.getTime() / 1000);
if (act.startTime > nowDate) {
return Promise.reject({code: 301, result: false, msg: '活动未开始'});
}
if (act.endTime < nowDate) {
return Promise.reject({code: 302, result: false, msg: '活动已过期'});
}
// 获取活动信息
let conf = await this.client.hgetallAsync(`turntable:${obj.act_id}`)
.then(conf => {
Object.keys(conf).forEach(key => {
if (conf[key] && !_.isNaN(Number(conf[key]))) {
conf[key] = Number(conf[key])
}
});
return conf;
});
let residueCount;
let uid = {
toString: () => {
return _.parseInt(obj.uid);
},
sessionKey: obj.sessionKey,
appVersion: obj.appVersion,
appSessionType: obj.sessionType
};
delete obj.sessionKey;
delete obj.appVersion;
delete obj.sessionType;
// 计算用户剩余次数校验
if (conf.times_type === 1) {
// 获取当天0点和23:59:59
let startTime = new Date(new Date().toLocaleDateString()).getTime();
let endTime = new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1).getTime();
let usedArr = await this.client.zrangebyscoreAsync(`turntable:${obj.act_id}:user:${obj.uid}:prize`, startTime, endTime);
if (usedArr.length > 100) {
await this.client.delAsync(`turntable:${obj.act_id}:user:${obj.uid}:prize`);
}
residueCount = conf.day_limit_times;
}
if (residueCount > 0) {
// 获取抽取到奖品
// 获取奖品信息
let prize = await this.client.lrangeAsync(`turntable:${obj.act_id}:prize`, 0, 7)
.then(prizes => {
return prizes.map(prize => {
return JSON.parse(prize);
})
});
// 获取每个奖品获取它们的中奖范围
let arr = {}, oldValue;
prize.map(function (value, index) {
if (value.chance) {
if (typeof(oldValue) === 'undefined') {
arr[index] = {maxValue: value.chance, leastValue: 0};
} else {
let maxValue = value.chance + oldValue;
let leastValue = oldValue;
arr[index] = {maxValue, leastValue};
}
oldValue = arr[index].maxValue;
}
});
// 比较概率获取中奖奖品
// 随机生成0-100的随机数
let random = Math.random() * 100;
// 判定随机数在奖品池子取件 选定中奖奖品
let getPrize, sendResult = {}, result;
for (let i in arr) {
if (arr[i].maxValue >= random && arr[i].leastValue < random) {
getPrize = prize[i];
break;
}
}
if (getPrize.type !== 1) {
// 校验剩余库存 减库存
let left = await this.client.getAsync(`turntable:${obj.act_id}:prize:${getPrize.prize_idx}:stock`);
if (left > 0) {
await this.client.decrAsync(`turntable:${obj.act_id}:prize:${getPrize.prize_idx}:stock`);
} else {
for (let p of prize) {
if (p.type === 1) {
getPrize = p;
break;
}
}
}
}
if (getPrize.type === 1) {
sendResult.code = 200;
getPrize.desc = '对不起,您没有中奖';
} else if (getPrize.type === 2) {
try {
// 调用java接口
sendResult = await this.get({
data: {
method: 'app.redpac.addRedpac',
actSource: 1001,
uid: uid,
redpacToken: getPrize.value
}
});
sendResult = sendResult || {};
sendResult.data = sendResult.data || {};
sendMessage(0, {}, {succeedTimes: sendResult.data.amount || 0}, 0);
if (sendResult.code === 200) {
if (!sendResult.data.amount) {
sendResult.code = 201; // 重复领取
} else {
getPrize.desc = '恭喜您获得' + sendResult.data.amount + '元红包';
}
}
} catch (e) {
logger.error(e);
sendMessage(0, {}, {message: e.message || 'interface error', stack: e}, 1);
}
} else if (getPrize.type === 3) {
try {
sendResult = await this.get({
data: {
method: 'app.coupons.couponsSend',
uid: uid,
coupon_send_token: getPrize.value
}
});
sendMessage(1, {}, {succeedTimes: 1}, 0);
if (sendResult && sendResult.code === 200) {
getPrize.desc = '恭喜您获得' + getPrize.name + '优惠券';
}
} catch (e) {
logger.error(e);
sendMessage(1, {}, {message: e.message || 'interface error', stack: e}, 1);
}
} else if (getPrize.type === 4) {
sendResult.code = 200;
getPrize.desc = '恭喜您获得' + getPrize.name;
}
// 插入数据库
if (sendResult.code !== 200) {
getPrize = null;
for (let item of prize) {
if (item.type === 1) {
getPrize = item;
break;
}
}
getPrize.desc = '对不起,您没有中奖';
}
let score = new Date().getTime();
getPrize.createTime = score;
result = await Promise.all([
this.client.zaddAsync(
`turntable:${obj.act_id}:user:${obj.uid}:prize`, score, `${JSON.stringify(getPrize)}:::${score}`),
this.client.lpushAsync(
`turntable:${obj.act_id}:prize:users`, `${obj.uid}:::${prizeType[getPrize.type]}:::${getPrize.name}:::${score}`)
]);
if (result) {
delete getPrize.chance;
delete getPrize.create_time;
delete getPrize.total;
delete getPrize.total_left;
delete getPrize.value;
return Promise.resolve(getPrize);
} else {
return Promise.reject({code: 305, result: false, msg: '服务错误,请稍等'});
}
} else {
return Promise.reject({code: 304, result: false, msg: '用户使用次数不足'});
}
} catch (e) {
logger.error(e);
return Promise.reject({code: 305, result: false, msg: '服务错误,请稍等'});
}
}
async getUserPrize(obj) {
// 兼容线上活动
if (+obj.act_id !== 44) {
try {
obj.act_id = parseInt(aes.decryptUid(obj.act_id), 10);
} catch (err) {
obj.act_id = 0;
}
}
if (!obj.act_id) {
return [];
}
try {
// 兼容线上活动奖品
if (+obj.act_id === 44) {
let oddPrizes = [];
try {
oddPrizes = await mysqlCli.query(
`select u.id, u.act_id act_id, u.prize_id prize_id, u.create_time createTime, p.name name,p.type type ,p.value value,p.img img
from act_wheel_surf_user u , act_wheel_surf_prize p where u.prize_id = p.id and u.act_id =:act_id and u.uid = :uid and type != :type
order by u.create_time desc`, {act_id: obj.act_id, uid: obj.uid, type: 1});
} catch(e) {
logger.error(e);
}
return this.client.zrevrangeAsync(`turntable:${obj.act_id}:user:${obj.uid}:prize`, 0, 300)
.then(prizes => {
return prizes.map(prize => {
return JSON.parse(prize.split(':::')[0]);
}).filter(prize => {
return prize.type !== 1;
}).concat(oddPrizes);
});
} else {
return await this.client.zrevrangeAsync(`turntable:${obj.act_id}:user:${obj.uid}:prize`, 0, 300)
.then(prizes => {
return prizes.map(prize => {
return JSON.parse(prize.split(':::')[0]);
}).filter(prize => {
return prize.type !== 1;
});
});
}
} catch (e) {
logger.error(e);
return Promise.reject({code: 305, result: false, msg: '服务错误,请稍等'});
}
}
}
module.exports = ActWheelSurfModelRedis;