daily-check-in.js 15.3 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 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
/**
 * 签到活动model
 * Created by qiujun on 2019/5/7.
 */
const _ = require('lodash');
const aes = require('../../../utils/aes');
const WheelSurfModel = require('./wheel-surf');
const PARENT_TABLE_NAME = 'dailysignin';
const TABLE_NAME = PARENT_TABLE_NAME + ':activity';

class DailyCheckInModel extends global.yoho.BaseModel {
  constructor(ctx) {
    super(ctx);
    this.redis = global.yoho.redis;
    this.client = this.redis.client;
    this.wheelSurfModel = new WheelSurfModel(ctx);
  }

  /**
   * 获取活动信息
   * @param actId
   * @returns {Promise.<void>}
   */
  async getActInfo(actId) {
    let idx = 0;

    try {
      idx = parseInt(aes.decryptUid(actId), 10) - 1;
    } catch (err) {
      return {
        code: 203,
        message: '无活动信息'
      };
    }

    if (idx || idx === 0) {
      return this.client.lrangeAsync(TABLE_NAME, idx, idx).then(act => {
        return JSON.parse(act[0]);
      });
    } else {
      return {
        code: 203,
        message: '无活动信息'
      };
    }
  }

  /**
   * 每日签到
   * @param data
   * @returns {Promise.<void>}
   */
  async checkInNormal(data) {
    if (data.uid && data.actId) {
      let actInfo = await this.getActInfo(data.actId);

      if (actInfo.code && actInfo.code === 203) { // 无活动信息,返回
        return actInfo;
      }
      let now = new Date(); // 今天的日期用于判断

      if (now.getTime() < parseInt(actInfo.startTime, 10) * 1000) {
        return {
          code: 203,
          message: '活动未开始'
        };
      }

      if (now.getTime() > parseInt(actInfo.endTime, 10) * 1000) {
        return {
          code: 203,
          message: '活动已结束'
        };
      }

      let normalWheelId = actInfo.normalWheelId;
      let checkInKey = `${PARENT_TABLE_NAME}:${actInfo.id}:user:${data.uid}:checkin`;

      let params = {
        act_id: normalWheelId,
        uid: data.uid,
        sessionKey: data.sessionKey,
        appVersion: data.appVersion,
        sessionType: data.appSessionType
      };

      let getUserCheckInData = await this.client.zrevrangeAsync(checkInKey, 0, 0); // 查询用户最近一次签到信息
      let isChecked = false;

      if (getUserCheckInData && getUserCheckInData.length > 0) { // 如果有签到信息,判断是否是今日签到的
        let checkInData = JSON.parse(getUserCheckInData[0]);
        let date = new Date(checkInData.createTime);

        if ((new Date(date.toLocaleDateString())).getTime() >= (new Date(now.toLocaleDateString())).getTime()) {
          isChecked = true;
        }
      }

      if (!isChecked) { // 没有签到的情况下,签到
        return this.wheelSurfModel.goPrize(params).then(prize => {
          if (prize.name && prize.type) { // 从大转盘接口返回的奖品信息

            let score = (new Date()).getTime();
            let checkInData = {
              actId: data.actId,
              wheelId: normalWheelId,
              prizeId: prize.id,
              prizeImg: prize.img,
              prizeDesc: prize.desc,
              prizeType: prize.type,
              createTime: score
            };

            return this.client.zaddAsync(checkInKey, score, JSON.stringify(checkInData)).then(() => {
              return Object.assign({}, {code: 200}, checkInData);
            });
          } else {
            return {
              code: 205,
              message: '未中奖',
              data: prize
            };
          }
        });
      } else {
        return {
          code: 201,
          message: '今天已经签到过咯~'
        };
      }
    }
  }

  /**
   * 对于实物中奖的用户,保存其中奖信息
   * @param data
   * @returns {Promise.<void>}
   */
  async saveUserInfo(data) {
    if (data.uid && data.actId) {
      let actId;

      try {
        actId = parseInt(aes.decryptUid(data.actId), 10);
      } catch (err) {
        return {
          code: 203,
          message: '无活动信息'
        };
      }
      let userPhoneKey = `${PARENT_TABLE_NAME}:${actId}:user:${data.uid}:info`;
      let allPrizeKey = `${PARENT_TABLE_NAME}:${actId}:prizelist`;
      let userCumulativeData = await this.getUserCumulativeData({uid: data.uid, actId: data.actId});


      if (userCumulativeData.cumPrize.length > 0) {
        let userInfo = await this.getUserInfo(data);

        if (!userInfo.hasPhoneNum) {
          let hasRealPrize = false; // 是否存在实物奖品
          let realPrizeArr = []; // 临时存储中到的实物奖品

          for (let i = 0; i < userCumulativeData.cumPrize.length; i++) {

            let prize = userCumulativeData.cumPrize[i];

            if (prize.prizeType === 4) {
              hasRealPrize = true;
              realPrizeArr.push(prize);
            }
          }

          if (hasRealPrize) { // 有实物奖品的情况下
            let score = (new Date()).getTime();
            let phoneData = {
              phone: data.phone.toString(),
              uid: data.uid
            };

            return this.client.zaddAsync(userPhoneKey, score, JSON.stringify(phoneData)).then(() => { // 往用户信息表添加信息
              return {
                code: 200,
                message: '保存成功'
              };
            });

          } else {
            return {
              code: 204,
              message: '无实物奖品中奖信息'
            };
          }
        } else {
          return {
            code: 203,
            message: '您已填写过手机号,请勿重复提交'
          };
        }
      } else {
        return {
          code: 204,
          message: '无中奖信息'
        };
      }
    }
  }

  /**
   * 获取用户是否填写过手机号信息
   * @param data
   * @returns {Promise.<void>}
   */
  async getUserInfo(data) {
    if (data.uid && data.actId) {
      let actId;

      try {
        actId = parseInt(aes.decryptUid(data.actId), 10);
      } catch (err) {
        return {
          code: 203,
          message: '无活动信息'
        };
      }
      let userPhoneKey = `${PARENT_TABLE_NAME}:${actId}:user:${data.uid}:info`;
      let userInfo = await this.client.zrangeAsync(userPhoneKey, 0, 0);

      if (userInfo && userInfo.length > 0) {
        return {
          code: 200,
          hasPhoneNum: 1
        };
      } else {
        return {
          code: 203,
          hasPhoneNum: 0
        };
      }
    }
  }

  /**
   * 获取此次活动所有获得实物奖品的人员列表
   * @param data
   * @returns {Promise.<void>}
   */
  async getWinnerList(data) {
    if (data.actId) {
      let actId;

      try {
        actId = parseInt(aes.decryptUid(data.actId), 10);
      } catch (err) {
        return {
          code: 203,
          message: '无活动信息'
        };
      }

      let prizeListKey = `${PARENT_TABLE_NAME}:${actId}:prizelist`;
      let result = await this.client.zrevrangeAsync(prizeListKey, 0, -1);
      let finalResult = [];

      for (let i = 0; i < result.length; i++) {
        let ret = {};
        let prize = JSON.parse(result[i]);

        let uid = prize.uid;
        let userInfoKey = `${PARENT_TABLE_NAME}:${actId}:user:${uid}:info`;
        let userInfo = await this.client.zrangeAsync(userInfoKey, 0, 0);


        if (userInfo && userInfo.length > 0) {
          let phone = JSON.parse(userInfo[0]).phone;

          ret.phone = phone.substring(0, 3) + '****' + phone.substring(7, 11);
          ret.prizeName = prize.prizeDesc;
          finalResult.push(ret);
        }
      }

      return finalResult;
    }
  }

  /**
   * 累计签到
   * @param data
   * @returns {Promise.<void>}
   */
  async checkInCumulative(data) {
    if (data.uid && data.actId) {
      let actInfo = await this.getActInfo(data.actId);
      let userCumulativeData = await this.getUserCumulativeData({uid: data.uid, actId: data.actId});

      if (actInfo.code && actInfo.code === 203) { // 无活动信息,返回
        return actInfo;
      }


      if (actInfo.prizeDayArr && actInfo.prizeDayArr.length > 0) {
        let totalDays = userCumulativeData.cumDays.length; // 累计已签到天数
        let prizeKey = `${PARENT_TABLE_NAME}:${actInfo.id}:user:${data.uid}:prize`;

        if (totalDays > 0) {
          for (let i = 0; i < actInfo.prizeDayArr.length; i++) {
            let day = actInfo.prizeDayArr[i]; // 配置的累计天数信息
            let daysCount = parseInt(day.count, 10); // 当前循环中累计天数的数量
            let wheelId = day.wheelId; // 累计天数信息中配置的大转盘id
            let params = {
              act_id: wheelId,
              uid: data.uid,
              sessionKey: data.sessionKey,
              appVersion: data.appVersion,
              sessionType: data.appSessionType
            };

            if (totalDays >= daysCount) { //  比较累计签到的天数是否大于活动设定的累计签到天数
              if (userCumulativeData.cumPrize.length > 0) { // 如果获得过签到奖品,则判断是否是已领取过对应的累计奖励
                let isGet = false;

                for (let j = 0; j < userCumulativeData.cumPrize.length; j++) {
                  let prizeGet = userCumulativeData.cumPrize[j];

                  if (parseInt(prizeGet.daysCount, 10) === daysCount) { // 如果获得的累计奖品的天数和当前循环的累计天数相同
                    isGet = true;
                  }
                }

                if (!isGet) {
                  return this.wheelSurfModel.goPrize(params).then(prize => { // 调用对应的大转盘获取奖品返回
                    if (prize.name && prize.type) {
                      let score = (new Date()).getTime();
                      let checkInData = {
                        actId: data.actId,
                        wheelId: wheelId,
                        prizeId: prize.id,
                        prizeImg: prize.img,
                        prizeDesc: prize.desc,
                        prizeType: prize.type,
                        daysCount: daysCount,
                        createTime: score
                      };

                      return this.client.zaddAsync(prizeKey, score, JSON.stringify(checkInData)).then(() => {
                        if (prize.type === 4) { // 实物奖品则记录进奖品列表
                          let allPrizeKey = `${PARENT_TABLE_NAME}:${actInfo.id}:prizelist`;
                          let prizeData = {
                            actId: data.actId,
                            decryptedId: actInfo.id,
                            uid: data.uid,
                            prizeId: prize.id,
                            prizeImg: prize.img,
                            prizeDesc: prize.desc.replace('恭喜您获得', ''),
                            prizeType: prize.type,
                            daysCount: daysCount,
                            createTime: score
                          };

                          return this.client.zaddAsync(allPrizeKey, score, JSON.stringify(prizeData)).then(() => {
                            return Object.assign({}, {code: 200, list: 'ok'}, checkInData);
                          });
                        }


                        return Object.assign({}, {code: 200}, checkInData);
                      });
                    } else {
                      return {
                        code: 205,
                        message: '服务器异常,请稍候再试',
                        data: prize
                      };
                    }
                  });
                }
              } else { // 如果没有获得过累计签到的奖品
                return this.wheelSurfModel.goPrize(params).then(prize => { // 调用对应的大转盘获取奖品返回
                  if (prize.name && prize.type) {
                    let score = (new Date()).getTime();
                    let checkInData = {
                      actId: data.actId,
                      wheelId: wheelId,
                      prizeId: prize.id,
                      prizeImg: prize.img,
                      prizeDesc: prize.desc,
                      prizeType: prize.type,
                      daysCount: daysCount,
                      createTime: score
                    };

                    return this.client.zaddAsync(prizeKey, score, JSON.stringify(checkInData)).then(() => {
                      if (prize.type === 4) { // 实物奖品则记录进奖品列表
                        let allPrizeKey = `${PARENT_TABLE_NAME}:${actInfo.id}:prizelist`;

                        let prizeData = {
                          actId: data.actId,
                          decryptedId: actInfo.id,
                          uid: data.uid,
                          prizeId: prize.id,
                          prizeImg: prize.img,
                          prizeDesc: prize.desc.replace('恭喜您获得', ''),
                          prizeType: prize.type,
                          daysCount: daysCount,
                          createTime: score
                        };

                        return this.client.zaddAsync(allPrizeKey, score, JSON.stringify(prizeData)).then(() => {
                          return Object.assign({}, {code: 200, list: 'ok'}, checkInData);
                        });
                      }
                      return Object.assign({}, {code: 200}, checkInData);
                    });
                  } else {
                    return {
                      code: 205,
                      message: '服务器异常,请稍候再试',
                      data: prize
                    };
                  }
                });
              }
            } else {
              return {
                code: 202,
                message: '未满足累计天数要求'
              };
            }
          }

          // 循环内全部未返回,则默认返回
          return {
            code: 202,
            message: '未满足累计天数要求'
          };
        } else { // 累计签到天数为0返回
          return {
            code: 202,
            message: '未满足累计天数要求'
          };
        }

      } else {
        return {
          code: 201,
          message: '无累计抽奖可用'
        };
      }
    }
  }

  /**
   * 获取签到累计天数
   * @param data
   * @returns {Promise.<{cumDays: *, cumGeted: (*|Array)}>}
   */
  async getUserCumulativeData(data) {
    if (data.uid && data.actId) {
      let actId = 0;

      try {
        actId = parseInt(aes.decryptUid(data.actId), 10);
      } catch (err) {
        return {
          code: 203,
          message: '无活动信息'
        };
      }

      if (actId) {
        let checkInKey = `${PARENT_TABLE_NAME}:${actId}:user:${data.uid}:checkin`;
        let cumPrizeKey = `${PARENT_TABLE_NAME}:${actId}:user:${data.uid}:prize`;

        let cumDays = await this.client.zrevrangeAsync(checkInKey, 0, -1); // 已签到天数
        let cumPrizeGeted = await this.client.zrevrangeAsync(cumPrizeKey, 0, -1); // 已获得的累计签到奖励
        let cumDaysResult = [];
        let cumPrizeResult = [];

        cumDays.map(day => {
          cumDaysResult.push(JSON.parse(day));
        });

        cumPrizeGeted.map(prize => {
          cumPrizeResult.push(JSON.parse(prize));
        });

        return {
          code: 200,
          cumDays: cumDaysResult,
          cumPrize: cumPrizeResult
        };
      }

    }

  }

}

module.exports = DailyCheckInModel;