friend.js 3.35 KB
/**
 * Created by Tommy Huang on 18/04/10.
 */
const config = require('config-lite')({
  config_basedir: __dirname,
  config_dir: 'config'
})
const Helper = require('./helper')
const _ = require('lodash')
const Op = require('sequelize').Op

const User = require('../models').User
const BorrowList = require('../models').BorrowList
const Friendship = require('../models').Friendship

exports.getList = async function (req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.query.userId
    const search = req.query.search || ''
    if (!userId)  throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    let friendships = await Friendship.findAll({where: {userId: userId}})
    let friendIds = _.map(friendships, 'friend_id')
    let list = await User.findAll({
      where: {
        id: friendIds,
        name: {
          [Op.like]: `%${search}%`
        }
      },
      attributes: ['id', 'name', 'headimgurl'],
    })
    const count = list.length
    res.json({
      success: 1,
      count: count,
      list: list
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `获取好友失败:${e.message}`
    })
  }
}

exports.getFriendInfo = async function (req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.query.userId
    const id = req.query.id
    if (!userId)  throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    const [friendship, friend] = await Promise.all([
      Friendship.findOne({where: {userId: userId, friendId: id}}),
      User.findOne({
        where: {id: id},
        attributes: ['id', 'name', 'headimgurl', 'phone'],
      })
    ])
    if (!friendship || !friend) throw new Error('好友不存在')
    const [borrow, credit] = await Promise.all([
      BorrowList.findAll({where:{
        borrowerId: friend.id,
        deleted: false,
        status: ['已生效']
      }}),
      BorrowList.findAll({where:{
        creditorId: friend.id,
        deleted: false,
        status: ['已生效']
      }}),
    ])
    const borrowInfo = buildBorrowRecordStatistics(borrow, 'borrow')
    const creditInfo = buildBorrowRecordStatistics(credit, 'credit')
    res.json({
      success: 1,
      user: friend,
      borrowInfo: borrowInfo,
      creditInfo: creditInfo
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `获取好友信息失败:${e.message}`
    })
  }
}

/**
 * 
 * @param {Array} list 历史借条列表
 * @param {String} type 借款:'borrow', 出借: ’credit‘
 */
function buildBorrowRecordStatistics(list, type) {
  const totalAmount = 0
  const times = list.length
  let peoples = 0
  const inOneDay = 0
  const effectiveAmount = 0
  let targetIds = []
  list.forEach((item) => {
    totalAmount += item.amount
    if (item.status === '已生效') {effectiveAmount += item.amount}
    if (item.start_date === item.end_date) {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
  }
}