user.js 14.5 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
/**
 * Created by Tommy Huang on 18/03/21.
 */

const config = require('config-lite')({
  config_basedir: __dirname,
  config_dir: 'config'
})
const moment = require('moment')
const axios = require('axios')
const jwt = require('jsonwebtoken')
const Helper = require('./helper')

const User = require('../models').User
const BorrowList = require('../models').BorrowList
const OverdueRecord = require('../models').OverdueRecord
const Redis = require('../models/redis')
const Op = require('sequelize').Op

exports.get = async function(req, res) {
  try {
    const expires = Date.now() + 2592000000
    var userToken
    if (process.env.NODE_ENV !== 'production') {
      let userId = 'oLP-es_k21Xzv-HgFMXTNFLlUMPY'
      let user = await User.findOne({
        where: {id: userId}
      })
      userToken = jwt.sign({
        iss: 'qicaidai',
        userId: user.id, 
        exp: expires
      }, config.jwt.key)
      res.json({
        success: 1,
        token: userToken,
        user: {
          id: user.id,
          username: user.username,
          name: user.name,  
          idNo: user.idNo,        
          headimgurl: user.headimgurl,
          phone: user.phone || '',
          needPhoneBind: !user.phoneBinded,
          needIdBind: !user.idBinded,
          needSetPassword: !user.password
        }
      })
      return
    }
    const code = req.query.code
    let userId, user, token, info, refreshToken
    userId = req.user.userId || ''
    console.log('userId:', userId)
    if (userId) {
      user = await User.findOne({
        where: {id: userId}
      })
    }
    if (user && user.refreshToken) {
      let tokenResult = await Helper.refreshUserWxToken(user.refreshToken)
      if (!tokenResult) throw new Error('刷新微信授权失败')
      userId = user.id
      token = tokenResult.access_token
      refreshToken = user.refreshToken
    } else if (code) {
      let ticketResult = await Helper.getUserWxAccessTokenInfo(code)
      if (!ticketResult) throw new Error('获取微信授权失败')
      userId = ticketResult.openid
      token = ticketResult.access_token
      refreshToken = ticketResult.refresh_token
    } else {
      throw new Error('非法参数')
    }
    info = await Helper.getUserWxInfo(token, userId)
    if (!info) throw new Error('拉取微信信息失败')
    if (!user) {
      user = await User.findOne({
        where: {id: info.openid}
      })
    }
    if (user) {
      await user.update({
        username: info.nickname,
        headimgurl: info.headimgurl,
        refreshToken: refreshToken
      })
    } else {
      user = await User.create({
        id: info.openid,
        username: info.nickname,
        headimgurl: info.headimgurl,
        refreshToken: refreshToken
      })
    }
    console.log(user.id)
    userToken = jwt.sign({
      iss: 'qicaidai',
      userId: user.id, 
      exp: expires
    }, config.jwt.key)
    res.json({
      success: 1,
      token: userToken,
      user: {
        id: user.id,
        name: user.name,
        username: info.nickname,
        headimgurl: info.headimgurl,
        phone: user.phone || '',
        needPhoneBind: !user.phoneBinded,
        needIdBind: !user.idBinded,
        needSetPassword: !user.password        
      }
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      redirect: config.entryURL,
      msg: `获取用户信息失败:${e.message}`
    })
  }
}

exports.getVerificationCode = async function(req, res) {
  try {
    const phone = req.query.phone
    const id = req.query.userId
    const idFromToken = req.user.userId
    const reg =  /^1[0-9]{10}$/
    if (!id)  throw new Error('参数错误')
    if (idFromToken !== id) throw new Error('token check fail')
    if (!reg.test(phone)) throw new Error('手机号码不正确')
    let [user, userByPhone ] = await Promise.all([
      User.findOne({where: {id: id}}),
      User.findOne({where: {phone: phone, phoneBinded: true}})
    ])
    if (userByPhone) throw new Error('该号码已注册')    
    if (!user) throw new Error('用户不存在')
    let date = moment().format('YYYY-MM-DD')
    let timesKey = `sms_${phone}_${date}`
    let frequencyKey = `fqy_${phone}_${date}`
    let [timesData, frequencyData] = await Promise.all([Redis.get(timesKey), Redis.get(frequencyKey)])
    if (frequencyData) throw new Error('获取验证码太频繁')
    if (timesData >= 6) throw new Error('今日获取验证码数量已达上限')
    let times = parseInt(timesData) || 0
    let [timeResult, frequencyResult] = await Promise.all([
      Redis.sendCommand("set", [timesKey, times + 1, 'ex', 86400]),
      Redis.sendCommand("set", [frequencyKey, 'exist', 'ex', 60])
    ])
    let send = await Helper.sendVerificationCode(phone)
    if (!send.success) throw new Error(send.msg)
    await user.update({
      verificationCode: send.code,
      phone: phone,
      codeTime: moment().format()
    })
    res.json({
      success: 1
    })
  } catch (e) {
    res.json({
      success: 0,
      msg: `获取验证码失败:${e.message}`
    })
  }
}

exports.bindPhone = async function(req, res) {
  try {
    const id = req.body.userId
    const idFromToken = req.user.userId
    const phone = req.body.phone
    const code = req.body.verificationCode
    if (!id || !phone || !code)  throw new Error('参数错误')
    if (idFromToken !== id) throw new Error('token check fail')
    let user = await User.findOne({
      where: {id: id}
    })
    if (!user) throw new Error('用户不存在')
    if (user.phone !== phone) throw new Error('修改手机号后请重新获取验证码')
    if (user.verificationCode !== code) throw new Error('验证码不正确')
    let codeTime = moment(user.codeTime).add(5, 'minutes')
    if (moment().isAfter(codeTime)) throw new Error('验证码已过期')
    const update = await user.update({
      phoneBinded: true
    })
    res.json({
      success: 1,
      phone: phone
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `绑定失败:${e.message}`
    })
  }
}

exports.bindId = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const id = req.body.userId
    const name = req.body.name || ''
    let idNo = req.body.idNo || ''
    let userInfo = {}
    if (!id || req.files.length !== 2 || !name || !idNo)  throw new Error('参数错误')
    if (idFromToken !== id) throw new Error('token check fail')
    if (idNo.length !== 18) throw new Error('身份证号长度不正确')
    if (idNo.endsWith('x')) idNo = idNo.slice(0, 17) + "X"
    const [user, idUsed] = await Promise.all([
      User.findOne({where: {id: id}}),
      User.findOne({where: {idNo: idNo}})      
    ])
    if (!user) throw new Error('用户不存在')
    if (user.idBinded) throw new Error('您已绑定过身份信息')
    if (idUsed) throw new Error('该身份证已被绑定过')
    var idFront, idBack
    req.files.forEach(file => {
      if (file.fieldname === 'idFront') {
        idFront = file
      } else if (file.fieldname === 'idBack') {
        idBack = file
      }
    })
    if (!idFront || !idBack) throw new Error('照片上传错误')
    if (idFront.size >= 2000000) {
      const compressed = await Helper.imageCompression(idFront.buffer, 1000)
      idFront = {
        buffer: compressed,
        mimetype: idFront.mimetype
      }
    }
    if (idBack.size >= 2000000) {
      const compressed = await Helper.imageCompression(idBack.buffer, 1000)
      idBack = {
        buffer: compressed,
        mimetype: idBack.mimetype
      }
    }
    const auth = Helper.tencentCloudAuthorization()
    const [frontResData, backResData] = await Promise.all([
      Helper.getIdORCResult(idFront.buffer, 0, auth),
      Helper.getIdORCResult(idBack.buffer, 1, auth)      
    ])
    console.log(frontResData.data)
    if (frontResData.code !== 0 || backResData.code !== 0) throw new Error('身份证识别失败,请上传更清晰的照片')
    if (frontResData.data.name !== name || frontResData.data.id !== idNo) {
      const {name_confidence_all, id_confidence_all} = frontResData.data
      name_confidence_all.forEach((confidence) => {
        if (confidence < 50) throw new Error('身份证识别失败,请上传更清晰的照片')
      })
      id_confidence_all.forEach((confidence) => {
        if (confidence < 50) throw new Error('身份证识别失败,请上传更清晰的照片')
      })
      throw new Error('身份证识别结果与提交信息不符,请确认信息后重试')
    }
    const idAuthResult = await Helper.idInfoAuth(frontResData.data.id, frontResData.data.name)
    if (idAuthResult.error_code === 0) {
      userInfo.name = idAuthResult.result.realName
      userInfo.idNo = idAuthResult.result.cardNo
      userInfo.gender = idAuthResult.result.details.sex === 1 ? '男' : '女'
      userInfo.nation = frontResData.data.nation
      userInfo.birth = idAuthResult.result.details.birth
      userInfo.address = frontResData.data.address
    } else if (idAuthResult.error_code === 90033 || idAuthResult.error_code === 90099) {
      throw new Error('身份信息验证未通过,请核实信息后再次提交')
    } else {
      throw new Error('身份信息验证失败,请稍候再试')
    }
    const [update, frontSave, backSave] = await Promise.all([
      user.update({
        idBinded: true,
        name: userInfo.name,
        gender: userInfo.gender,
        nation: userInfo.nation,
        birth: userInfo.birth,
        address: userInfo.address,
        idNo: userInfo.idNo,
        authority: backResData.data.authority,
        validDate: backResData.data.valid_date,
      }),
      Helper.writeFile(`${config.img.idImg}/${frontResData.data.id}-Front.${idFront.mimetype.split('/')[1]}`, idFront.buffer),
      Helper.writeFile(`${config.img.idImg}/${frontResData.data.id}-Back.${idBack.mimetype.split('/')[1]}`, idBack.buffer)
    ])
    res.json({
      success: 1,
      name: frontResData.data.name
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: e.message
    })
  }
}

exports.setPassword = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const id = req.body.userId
    const password = req.body.password || ''
    if (!id || !password)  throw new Error('参数错误')
    if (idFromToken !== id) throw new Error('token check fail')
    if (password.length !== 6) throw new Error('密码至少为6')
    const user = await User.findOne({where: {id: id}})
    if (!user) throw new Error('用户不存在')
    if (user.password) throw new Error('您已设置过密码')
    let savedPasswd = await Helper.buildPassword(password)
    let update = await user.update({
      password: savedPasswd
    })
    res.json({
      success: 1,
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `${e.message}`
    })
  }
} 

exports.getSelfInfo = async function (req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.query.userId
    if (!userId)  throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    const [self, borrow, credit, allOverDue] = await Promise.all([
      User.findOne({
        where: {id: userId},
        attributes: ['id', 'name', 'headimgurl', 'phone'],
      }),
      BorrowList.findAll({where:{
        borrowerId: userId,
        deleted: false,
        status: ['已生效', '已逾期', '已还清']
      }}),
      BorrowList.findAll({where:{
        creditorId: userId,
        deleted: false,
        status: ['已生效', '已逾期', '已还清']
      }}),
      OverdueRecord.findAll({
        where: {
          userId: userId,
          status: {
            [Op.not]: '已展期'
          }
        },
        include: [{
          model: BorrowList,
          required: true
        }]
      })
    ])
    const borrowInfo = buildBorrowRecordStatistics(borrow, 'borrow')
    const creditInfo = buildBorrowRecordStatistics(credit, 'credit')
    const overdueInfo = buildOverdueRecordStatistics(allOverDue)
    res.json({
      success: 1,
      user: self,
      borrowInfo: borrowInfo,
      creditInfo: creditInfo,
      overdueInfo: overdueInfo
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `获取用户信息失败:${e.message}`
    })
  }
}

/**
 * 
 * @param {Array} list 历史借条列表
 * @param {String} type 借款:'borrow', 出借: ’credit‘
 */
function buildBorrowRecordStatistics(list, type) {
  let totalAmount = 0
  let times = list.length
  let peoples = 0
  let inOneDay = 0
  let effectiveAmount = 0
  let targetIds = []
  list.forEach((item) => {
    totalAmount += item.amount
    if (item.status === '已生效' || item.status === '已逾期') {effectiveAmount += item.amount}
    if (item.startDate === item.endDate) {inOneDay++}
    let targetId = type === 'borrow' ? item.creditorId : item.borrowerId
    targetIds.push(targetId)
  })
  targetIds = new Set(targetIds)
  peoples = targetIds.size
  const inOneDayRate = times === 0 ? 0 : (Math.floor(inOneDay/times * 10000) / 100)
  return {
    totalAmount: totalAmount,
    times: times,
    effectiveAmount: effectiveAmount,
    inOneDayRate: inOneDayRate,
    peoples: peoples
  }
}

/**
 * 
 * @param {Array} list 历史逾期记录列表
 */
function buildOverdueRecordStatistics(list) {
  let totalTime = list.length
  let totalAmount = 0
  let sevenDayTime = 0
  let sevenDayAmount = 0
  let nowTime = 0
  let nowAmount = 0
  list.forEach(item => {
    totalAmount += item.borrow_list.amount
    if (item.status === '未还清') {
      nowTime++
      nowAmount+= item.borrow_list.amount
      if (moment().diff(moment(item.startDate, 'days')) >= 7) {
        sevenDayTime++
        sevenDayAmount+= item.borrow_list.amount
      }
    } else {
      if (moment(item.endDate).diff(moment(item.startDate, 'days')) >= 7) {
        sevenDayTime++
        sevenDayAmount+= item.borrow_list.amount
      }
    }
  })
  return {
    totalTime,
    totalAmount,
    sevenDayTime,
    sevenDayAmount,
    nowTime,
    nowAmount,
  }
}

exports.search = async (req, res) => {
  try {
    const name = req.query.name
    const phone = req.query.mobile
    if (!name || !phone) throw new Error('参数错误')
    const user = await User.findOne({
      where: {
        name: name,
        phone: phone
      }
    })
    if (user) {
      res.json({
        success: 1,
        notFound: false,
        id: user.id
      })
      return
    } else {
      res.json({
        success: 1,
        notFound: true,
      })
    }
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: e.message
    })
  }
}