iou.js 10 KB
/**
 * Created by Tommy Huang on 18/04/02.
 */
const config = require('config-lite')({
  config_basedir: __dirname,
  config_dir: 'config'
})
const moment = require('moment')
const uuid = require('uuid/v4')
const qr = require('qr-image')
const Helper = require('./helper')

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

exports.create = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const id = req.body.userId
    const amount = parseInt(req.body.amount) || 0
    const role = req.body.role
    const target = req.body.target
    const start = req.body.start
    const end = req.body.end
    const rate = req.body.rate
    const rateValue = parseFloat(req.body.rateValue)
    const usage = req.body.usage
    const explanation = req.body.explanation || ''
    const imgs = req.files || []
    if (!id || !role || !target || !start || !end || !rate || !rateValue || !usage ||!amount)  throw new Error('参数错误')
    if (idFromToken !== id) throw new Error('token check fail')
    if (amount <= 0) throw new Error('非法的借款金额')
    if (parseInt(rate.slice(0, rate.length - 1)) !== rateValue * 100 || rateValue < 0.01 || rateValue > 0.24) throw new Error('非法利率参数')
    const startDate = moment(start)
    const endDate = moment(end)
    if (!(startDate.isBefore(endDate))) throw new Erro('还款日期最早为借款日期后一日')
    const user = await User.findOne({where: {id: id}})
    if (!user) throw new Erro('用户不存在')
    let imgSrc = await Promise.all(imgs.map(async (item) => {
      let fileName = `${uuid()}.${item.mimetype.split('/')[1]}`
      await Helper.writeFile(`${config.img.iouImg}/${fileName}`, item.buffer)
      return fileName
    }))
    imgSrc = imgSrc.join(',')
    let newBorrowList = {
      id: uuid(),
      amount: amount,
      startDate: startDate.format(),
      endDate: endDate.format(), 
      rate: rateValue,
      usage: usage,
      explanation: explanation,
      imgs: imgSrc,
      targetName: target,
      sponsorId: user.id
    }
    if (role === 'borrower') {
      newBorrowList.borrowerId = user.id
    } else {
      newBorrowList.creditorId = user.id
    }
    let result = await BorrowList.create(newBorrowList)
    res.json({
      success: 1,
      id: result.id
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `创建失败:${e.message}`
    })
  }
}

exports.get = async function (req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.query.userId
    const id = req.query.id
    
    if (!id || !userId) throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    let info = await BorrowList.findOne({
      where: {
        id: id,
        deleted: false
      },
      include: [{
        model: User,
        required: false,
        as: 'Borrower',
        attributes: ['id', 'name', 'username', 'headimgurl']
      }, {
        model: User,
        required: false,
        as: 'Creditor',
        attributes: ['id', 'name', 'username', 'headimgurl']
      }]
    })
    if (!info) throw new Error('借条不存在')
    if (info.status === '未发起' && info.sponsorId !== userId) throw new Error('借条不存在')
    if (info.status !== '待确认' && info.sponsorId !== userId && info.creditorId !== userId && info.borrowerId !== userId) throw new Error('借条不存在')
    res.json({
      success: 1,
      info: info
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `获取失败:${e.message}`
    })
  }
}

exports.submitIOU = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.body.userId
    const id = req.body.id
    const password = req.body.password
    if (!id || !userId || !password )  throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    let [user, list] = await Promise.all([
      User.findOne({where: {id: userId}}),
      BorrowList.findOne({where: {id: id, sponsorId: userId, status: '未发起'}})
    ]) 
    if (!user) throw new Error('用户不存在')
    if (!list) throw new Error('未找到对应的借条')
    if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
    const shareUrl = Helper.buildShareUrl(list.id)
    const qrImg = qr.imageSync(shareUrl, { type: 'svg' })        
    let update = {
      qr: qrImg
    }
    if (user.id === list.creditorId) {
      update.creditorAgree = true
      update.status = '待确认'
    }
    if (user.id === list.borrowerId) {
      update.borrowerAgree = true
      update.status = '待确认'
    }
    
    let result = await list.update(update)
    res.json({
      success: 1,
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `借条提交失败:${e.message}`
    })
  }
}

exports.deleteIOU = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.body.userId
    const id = req.body.id
    const password = req.body.password
    if (!id || !userId || !password )  throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    let [user, list] = await Promise.all([
      User.findOne({where: {id: userId}}),
      BorrowList.findOne({where: {id: id, sponsorId: userId, status: '未发起'}})
    ]) 
    if (!user) throw new Error('用户不存在')
    if (!list) throw new Error('未找到对应的借条')
    if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
    let result = await list.update({
      deleted: true
    })
    res.json({
      success: 1,
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `借条删除失败:${e.message}`
    })
  }
}

exports.comfirmIOU = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.body.userId
    const id = req.body.id
    const password = req.body.password
    if (!id || !userId || !password )  throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    let [user, list] = await Promise.all([
      User.findOne({where: {id: userId}}),
      BorrowList.findOne({where: {id: id, status: '待确认'}})
    ]) 
    if (!user) throw new Error('用户不存在')
    if (!list) throw new Error('未找到对应的借条')
    if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
    if (user.name !== list.targetName) throw new Error('借条信息与您的身份信息不符,无法确认该借条')
    let update = {}
    if (list.creditorId && list.creditorAgree) {
      update.borrowerId = user.id
      update.borrowerAgree = true      
      update.status = '已生效'
    }
    if (list.borrowerId && list.borrowerAgree) {
      update.creditorId = user.id
      update.creditorAgree = true   
      update.status = '已生效'
    }
    let result = await list.update(update)
    res.json({
      success: 1,
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `借条确认失败:${e.message}`
    })
  }
}

exports.deleteIOU = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.body.userId
    const id = req.body.id
    const password = req.body.password
    if (!id || !userId || !password )  throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    let [user, list] = await Promise.all([
      User.findOne({where: {id: userId}}),
      BorrowList.findOne({where: {id: id, sponsorId: userId, status: '未发起'}})
    ]) 
    if (!user) throw new Error('用户不存在')
    if (!list) throw new Error('未找到对应的借条')
    if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
    let result = await list.update({
      deleted: true
    })
    res.json({
      success: 1,
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `借条删除失败:${e.message}`
    })
  }
}

exports.rejectIOU = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.body.userId
    const id = req.body.id
    const password = req.body.password
    if (!id || !userId || !password )  throw new Error('参数错误')
    if (idFromToken !== userId) throw new Error('token check fail')
    let [user, list] = await Promise.all([
      User.findOne({where: {id: userId}}),
      BorrowList.findOne({where: {id: id, sponsorId: userId, status: '待确认'}})
    ]) 
    if (!user) throw new Error('用户不存在')
    if (!list) throw new Error('未找到对应的借条')
    if (!Helper.passwdCheck(password, user.password)) throw new Error('交易密码不正确')
    if (user.name !== list.targetName) throw new Error('借条信息与您的身份信息不符,无法驳回该借条')    
    let result = await list.update({
      status: '已驳回'
    })
    res.json({
      success: 1,
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `借条删除失败:${e.message}`
    })
  }
}

exports.shareInfo = async function(req, res) {
  try {
    const idFromToken = req.user.userId
    const userId = req.query.userId
    const id = req.query.id
    if (!id || !userId)  throw new Error('未找到对应的借条')
    if (idFromToken !== userId) throw new Error('token check fail')
    let list = await BorrowList.findOne({
      where: {
        id: id, 
        sponsorId: userId, 
        status: '待确认'
      }
    })
    if (!list) throw new Error('未找到对应的借条')
    const shareUrl = Helper.buildShareUrl(list.id)
    let qrImg = list.qr
    if (!qrImg) {
      qrImg = qr.imageSync(shareUrl, { type: 'svg' })        
      await list.update({qr: qrImg})
    }
    res.json({
      success: 1,
      img: qrImg,
      url: shareUrl
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: `${e.message}`
    })
  }
}