iou.js 2.4 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 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.utc().format(),
      endDate: endDate.utc().format(), 
      rate: rateValue,
      usage: usage,
      explanation: explanation,
      imgs: imgSrc,
      targetName: target,
    }
    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}`
    })
  }
}