credit.js 8.21 KB
/**
 * Created by Tommy Huang on 18/03/21.
 */
const config = require('config-lite')({
  config_basedir: __dirname,
  config_dir: 'config'
})
const axios = require('axios')
const moment = require('moment')
const qs = require('querystring')
const uuid = require('uuid')
const Sequelize = require('sequelize')
const sequelize = require('../models/db.js').db
const Task = require('../models').Task
const User = require('../models').User
const Credit = require('../models').Credit
const TelecomReport = require('../models').TelecomReport
const CallRecord = require('../models').CallRecord
const Op = require('sequelize').Op

exports.submitTaskId = async (req, res) => {
  try {
    const id = req.user.userId
    const taskId = req.body.taskId || ''
    const userId = req.body.userId || ''
    if (!userId || !taskId) throw new Error('参数不全')
    if (id !== userId) throw new Error('token check fail')
    const task = await Task.findOne({where: {
      taskId: taskId,
      userId: userId
    }})
    console.log(task)
    if (!task) {
      const result = await Task.create({
        id: uuid(),
        taskId: taskId,
        userId: userId,
        kind: '运营商'
      })
      console.log(result)
    }
    res.json({
      success: 1
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: e.message
    })
  }
}

exports.submitBaseInfo = async (req, res) => {
  try {
    const id = req.user.userId
    const {wechatId, userId, area, address, contactAName, contactAPhone, contactARole, contactBName, contactBPhone, contactBRole} = req.body
    if (!wechatId || !userId || !area || !address || !contactAName || !contactAPhone || !contactARole || !contactBName || !contactBPhone || !contactBRole) throw new Error('参数错误')
    if (id !== userId) throw new Error('token验证失败')
    const item = {
      wechatAccount: wechatId,
      area: area,
      address: address,
      contactA: contactAName,
      contactAPhone: contactAPhone,
      contactARole: contactARole,
      contactB: contactBName,
      contactBPhone: contactBPhone,
      contactBRole: contactBRole,
      baseCreatedTime: moment().format()
    }
    const record = await Credit.findOne({where: {userId: userId}})
    if (record) {
      const update = await record.update(item)
      res.json({
        success: 1
      })
      return
    }
    const user = await User.findOne({where: {id: userId}})
    item.id = uuid()
    item.name = user.name
    item.idNo = user.idNo
    item.userId = user.id
    item.phone = user.phone
    const create = await Credit.create(item)
    res.json({
      success: 1
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: e.message
    })
  }
}

exports.getStatus = async (req, res) => {
  try {
    const id = req.user.userId
    const userId = req.query.userId
    if (id !== userId) throw new Error('token验证失败')
    const [basic, telecomTask] = await Promise.all([
      Credit.findOne({where: {userId: userId}}),
      Task.findOne({
        where: {
          userId: userId,
          kind: '运营商',
        },
        order: [['created_at', 'DESC']]
      })
    ]) 
    console.log()
    let status = {
      base: {
        status: '未填写'
      },
      mobile: {
        status: '未采集'
      }
    }
    if (basic) {
      status.base.status = '已填写'
      status.base.time = moment(basic.baseCreatedTime).format('YYYY-MM-DD')
    }
    if (telecomTask && telecomTask.status === '成功') {
      status.mobile.status = '已采集'
      status.mobile.time = moment(telecomTask.updated_at).format('YYYY-MM-DD')
    }
    if (telecomTask && telecomTask.status === '处理中') {
      status.mobile.status = '处理中'
      status.mobile.time = moment(telecomTask.updated_at).format('YYYY-MM-DD')
    }
    res.json({
      success: 1,
      status: status
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: e.message
    })
  }
}

exports.getReport = async(req, res) => {
  try {
    const id = req.user.userId
    const userId = req.query.userId
    let targetId = req.query.id
    let report = {}
    let mobile = {}
    if (!userId) throw new Error('参数错误')
    if (id !== userId) throw new Error('token验证失败')
    if (!targetId) {targetId = userId}
    const credit= await Credit.findOne({
      where: {
        userId: targetId
      }
    })
    if (!credit) {
      res.json({
        success: 1,
        hasReport: false,
      })
      return
    }
    const telecom = await TelecomReport.findOne({
      where: {
        userId: targetId
      },
      include: [{
        model: CallRecord,
        required: false,
        where: {

        }
      }],
      order: [['created_at', 'DESC']]
    })
    if (!telecom) {
      res.json({
        success: 1,
        hasReport: false,
      })
      return
    }
    report.name = credit.name
    report.wechatAccount = credit.wechatAccount
    report.phone = credit.phone
    report.idNo = `${credit.idNo[0]}****************${credit.idNo[17]}`
    report.address = credit.address.slice(0, credit.address.length / 2) + '******'
    report.contactA = credit.contactA[0].padEnd(credit.contactA.length, '*')
    report.contactB = credit.contactB[0].padEnd(credit.contactB.length, '*')
    report.contactAPhone = credit.contactAPhone.slice(0,3) + '****' + credit.contactAPhone.slice(7)
    report.contactBPhone = credit.contactBPhone.slice(0,3) + '****' + credit.contactBPhone.slice(7)
    report.contactARole= credit.contactARole
    report.contactBRole= credit.contactBRole
    report.contactATime = credit.contactATime
    report.contactBTime = credit.contactBTime
    report.contactAAmount = credit.contactAAmount
    report.contactBAmount = credit.contactBAmount
    mobile.netAge = telecom.netAge
    mobile.totalCallCount = telecom.totalCallCount
    mobile.totalCallTime = telecom.totalCallTime
    mobile.createdAt = moment(telecom.created_at).format("YYYY-MM-DD")
    mobile.contactNum = telecom.contactNum    
    report.mobile = mobile
    report.update = moment(telecom.created_at).isAfter(moment(credit.baseCreatedTime)) ? moment(telecom.created_at).format("YYYY-MM-DD") : moment(credit.baseCreatedTime).format("YYYY-MM-DD")
    res.json({
      success: 1,
      hasReport: true,
      report: report
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: e.message
    })
  }
}

exports.getCallRecord = async (req, res) => {
  try {
    const id = req.user.userId
    const userId = req.query.userId
    let targetId = req.query.id
    let report = {}
    let mobile = {}
    if (!userId) throw new Error('参数错误')
    if (id !== userId) throw new Error('token验证失败')
    if (!targetId) {targetId = userId}
    const telecom = await TelecomReport.findOne({
      where: {
        userId: targetId
      },
      order: [['created_at', 'DESC']]
    })
    if (!telecom) {
      res.json({
        success: 1,
        hasReport: false,
      })
      return
    }
    let [callFrequencyAnalysis, callTimeAnalysis] = await Promise.all([
      sequelize.query(`SELECT concat_ws('****', substring("call_other_number", 1, 3), substring("call_other_number", 8, 4)) AS "callOtherNumber", 
                      COUNT('callOtherNumber') AS "times" FROM "call_records" AS "call_record" 
                      WHERE "call_record"."telecom_report_id" = '${telecom.id}' 
                      AND "call_record"."call_other_number" != '未知' 
                      GROUP BY "callOtherNumber" 
                      ORDER BY "times" DESC limit 5;`),
      sequelize.query(`SELECT concat_ws('****', substring("call_other_number", 1, 3), substring("call_other_number", 8, 4)) AS "callOtherNumber", 
                       sum("call_time") AS "sum" FROM "call_records" AS "call_record" 
                       WHERE "call_record"."telecom_report_id" = '${telecom.id}' 
                       AND "call_record"."call_other_number" != '未知' 
                       GROUP BY "callOtherNumber" 
                       ORDER BY "sum" DESC limit 5;`)
    ]) 
    res.json({
      success: 1,
      hasReport: true,
      callFrequencyAnalysis: callFrequencyAnalysis[0],
      callTimeAnalysis: callTimeAnalysis[0]
    })
  } catch (e) {
    console.log(e)
    res.json({
      success: 0,
      msg: e.message
    })
  }
}