zl程序教程

您现在的位置是:首页 >  其他

当前栏目

eggjs 怎么实现月度账单统计接口?

2023-03-14 22:37:35 时间

原型分析


我们可以先看一下,这个统计页面原型分成了3个部分,第一个部分有月份,月总支出,月总收入,第二三部分,都是统计了支出跟收入两大类型下的不同消费类型的占比,只是展示形式不一样。

03f16be0385649e9b708944c50d49802.png


需要返回的数据结构

totalExpense, // 当月总支出
totalIncome, // 当月总收入
dataList: [{
    number: 11.99, // 支出或收入数量
    pay_type: 1, // 支出或消费类型值
    type_id: 1, // 消费类型id
    type_name: "餐饮" // 消费类型名称
},...], // 列表数据


月度账单统计接口实现


我们需要在控制层新增 analysis.js 文件


1、控制层编写 monthBill 方法


'use strict';

const Controller = require('egg').Controller;

class AnalysisController extends Controller {
  async monthBill() {
    const { ctx, app } = this;
    try {
      // 1、获取查询参数
      const { billDate } = ctx.query;
      console.log('1、获取查询参数',billDate);
      // 2、参数判空
      if (!billDate) {
        ctx.body = {
          status: 400,
          desc: '参数错误',
          data: null
        }
        return;
      }
      // 3、拿到 token 获取用户信息 user_id
      const token = ctx.request.header.authorization;
      const decode = await app.jwt.verify(token, app.config.jwt.secret);
      if (!decode) return;
      let user_id = decode.id;
      console.log('2、拿到 token 获取用户信息 user_id',user_id);
      // 4、获取月度账单统计数据
      const monthBillResult = await ctx.service.analysis.monthBill(user_id, billDate);
      const monthBillList = JSON.parse(JSON.stringify(monthBillResult));
      console.log('3、获取月度账单统计数据',monthBillResult,monthBillList);
      // 累加相同的消费类型 type_id 生成新的数组返回
      let dataList = monthBillList.reduce((curr, next) => {
        const index = curr.findIndex(item => item.type_id == next.type_id)
        if (index == -1) {
          curr.push({
            type_id: next.type_id,
            type_name: next.type_name,
            pay_type: next.pay_type,
            number: Number(next.amount)
          })
        }
        if (index > -1) {
          curr[index].number += Number(next.amount);
        }
        return curr;
      }, []);
      // 当月总支出:支付类型:1:支出,2:收入
      let totalExpense = monthBillList.reduce((curr, next) => {
        if (next.pay_type === 1) {
          curr += Number(next.amount);
          return curr;
        }
        return curr;
      }, 0).toFixed(2); 
      // 当月总收入:支付类型:1:支出,2:收入
      let totalIncome = monthBillList.reduce((curr, next) => {
        if (next.pay_type === 2) {
          curr += Number(next.amount);
          return curr;
        }
        return curr;
      }, 0).toFixed(2);
      console.log('当月总支出:',totalExpense, '当月总收入:',totalIncome);
      ctx.body = {
        status: 200,
        desc: '请求成功',
        data: {
          totalExpense, // 当月总支出
          totalIncome, // 当月总收入
          dataList: dataList, // 列表数据
        }
      }
    } catch (error) {
      console.log(error);
      ctx.body = {
        status: 500,
        desc: '系统错误',
        data: null
      }
    }
  }
}

module.exports = AnalysisController;



2、服务层编写 monthBill 方法

我们需要在服务层新增 analysis.js 文件

'use strict';

const Service = require('egg').Service;

class AnalysisService extends Service {
  // 获取月份所有账单数据
  async monthBill(user_id, month) {
    const { app } = this;
    try {
      let sql = "select * from `kaimo-cost`.bill b where user_id = "+ user_id + " and DATE_FORMAT(b.date,'%Y-%m') = '" + month + "'";
      console.log('获取月份所有账单数据', sql);
      const result = await app.mysql.query(sql);
      return result;
    } catch (error) {
      console.log(error);
      return null;
    }
  }
}
module.exports = AnalysisService;


3、路由配置

// 获取月度统计账单
router.get('/api/analysis/monthBill', verify_token, controller.analysis.monthBill);



测试


我们输入参数,不要忘记头部 token。

76a56a2dc3a04fd0bb44c1c52088bec6.png


没有数据:

6610397960b943afaaea8f956242cb73.png


不传参数:

99fde860c5ef44388bc966c7e6c23714.png