【山竹记账后端】15.给统计数据分组


大纲链接 §

[toc]


get '/api/v1/items/summary'

  1. 写测试
  2. 写代码
  3. 写文档(测试代码)

功能

  • 切换类型:支出/收入
  • 日期范围(按照每天来统计)显示金额折线图
  • 根据标签的分类金额显示饼状图占比
  • 账目排名-计量表

1. 按时间分组 ⇧

前端需要传参示例,响应数据结构 ⇧

get '/api/v1/items/summary?group_by=happened_at&kind&start&end'

  • group_by=happened_at 按照发生时间分组
  • kind 筛选支出/收入
  • start 开始时间
  • end 结束时间
  • 返回响应数据结构:

    1
    2
    3
    4
    5
    6
    7
    8
    
    {
    "groups": [
    { "happened_at": "2027-01-01", "amount": 990_00 },
    { "happened_at": "2027-01-02", "amount": 990_00 },
    { "happened_at": "2027-01-03", "amount": 990_00 },
    ],
    "total": 1_000_00
    }

get '/api/v1/items/summary?group_by=tag_id&kind&start&end'

  • group_by=tag_id 按照标签分组
  • kind 筛选支出/收入
  • start 开始时间
  • end 结束时间
  • 返回响应数据结构:

    1
    2
    3
    4
    5
    6
    7
    8
    
    {
    "groups": [
    { "tag_id": 12, "amount": 9_100_00 },
    { "tag_id": 15, "amount": 100_00 },
    { "tag_id": 21, "amount": 10_00 },
    ],
    "total": 1_000_00
    }

添加api路由 ⇧

config/routes.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
  get "/", to: "home#index"

  namespace :api do
    namespace :v1 do
      # /api/v1
      resources :validation_codes, only: [ :create ]
      resource :session, only: [ :create, :destroy ]
      resource :me, only: [ :show ]
      resources :items, exclude: [ :put ] do
        collection do
          get :summary
        end
      end
      resources :tags, exclude: [ :put ]
    end
  end
end
  • 输入命令 bin/rails routes 查看生成的路由

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
                                  Prefix Verb   URI Pattern                                                                                       Controller#Action
                                         GET    /                                                                                                 home#index
                 api_v1_validation_codes POST   /api/v1/validation_codes(.:format)                                                                api/v1/validation_codes#create
                          api_v1_session DELETE /api/v1/session(.:format)                                                                         api/v1/sessions#destroy
                                         POST   /api/v1/session(.:format)                                                                         api/v1/sessions#create
                               api_v1_me GET    /api/v1/me(.:format)                                                                              api/v1/mes#show
                    summary_api_v1_items GET    /api/v1/items/summary(.:format)                                                                   api/v1/items#summary {:exclude=>[:put]}
                            api_v1_items GET    /api/v1/items(.:format)                                                                           api/v1/items#index {:exclude=>[:put]}
                                         POST   /api/v1/items(.:format)                                                                           api/v1/items#create {:exclude=>[:put]}
                             api_v1_item GET    /api/v1/items/:id(.:format)                                                                       api/v1/items#show {:exclude=>[:put]}
                                         PATCH  /api/v1/items/:id(.:format)                                                                       api/v1/items#update {:exclude=>[:put]}
                                         PUT    /api/v1/items/:id(.:format)                                                                       api/v1/items#update {:exclude=>[:put]}
                                         DELETE /api/v1/items/:id(.:format)                                                                       api/v1/items#destroy {:exclude=>[:put]}
                             api_v1_tags GET    /api/v1/tags(.:format)                                                                            api/v1/tags#index {:exclude=>[:put]}
                                         POST   /api/v1/tags(.:format)                                                                            api/v1/tags#create {:exclude=>[:put]}
                              api_v1_tag GET    /api/v1/tags/:id(.:format)                                                                        api/v1/tags#show {:exclude=>[:put]}
                                         PATCH  /api/v1/tags/:id(.:format)                                                                        api/v1/tags#update {:exclude=>[:put]}
                                         PUT    /api/v1/tags/:id(.:format)                                                                        api/v1/tags#update {:exclude=>[:put]}
                                         DELETE /api/v1/tags/:id(.:format)                                                                        api/v1/tags#destroy {:exclude=>[:put]}
  • 找到 /api/v1/items/summary


测试用例代码 ⇧

spec/requests/api/v1/items_spec.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
require 'rails_helper'

RSpec.describe "Api::V1::Items", type: :request do
  describe "获取账目列表(分页)" do
    # ...
  end

  describe "创建账目" do
    # ...
  end

  describe "统计账目数据" do
    it "按天分组" do
      user = User.create email: '1@163.com'
      tag = Tag.create! name: 'tag1', sign: '🍎', user_id: user.id
      happened_at_1 = Time.now - 6.day
      happened_at_2 = Time.now - 3.day
      happened_at_3 = Time.now - 2.day
      Item.create! kind: "expenses", amount: 100, happened_at: happened_at_1,
        user_id: user.id, tags_id: [tag.id]
      Item.create! kind: "expenses", amount: 200, happened_at: happened_at_1,
        user_id: user.id, tags_id: [tag.id]
      Item.create! kind: "expenses", amount: 100, happened_at: happened_at_2,
        user_id: user.id, tags_id: [tag.id]
      Item.create! kind: "expenses", amount: 200, happened_at: happened_at_2,
        user_id: user.id, tags_id: [tag.id]
      Item.create! kind: "expenses", amount: 100, happened_at: happened_at_3,
        user_id: user.id, tags_id: [tag.id]
      Item.create! kind: "expenses", amount: 200, happened_at: happened_at_3,
        user_id: user.id, tags_id: [tag.id]

      get '/api/v1/items/summary',
        headers: user.generate_auth_header,
        params: {
          kind: 'expenses',
          group_by: 'happened_at',
          happened_after: Time.now - 7.day,
          happened_before: Time.now + 1.day
        }
      expect(response).to have_http_status :ok
      json = JSON.parse response.body
      expect(json['group'].size).to eq 3
      expect(json['group'][0]['happened_at']).to eq happened_at_1.iso8601
      expect(json['group'][0]['amount']).to eq 300
      expect(json['group'][1]['happened_at']).to eq happened_at_2.iso8601
      expect(json['group'][1]['amount']).to eq 300
      expect(json['group'][2]['happened_at']).to eq happened_at_3.iso8601
      expect(json['group'][2]['amount']).to eq 300
      expect(json['total']['amount']).to eq 900
    end
  end

  # TODO: 添加更多测试用例
end
  • 运行 rspec spec/requests/api/v1/items_spec.rb:155 报错
  • 之后需要实现 controller

使用按happened_at分组的统计逻辑 ⇧

app/controllers/api/v1/items_controller.rb 添加 summary 方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Api::V1::ItemsController < ApplicationController
  # 分页查询账目.
  # @return [Object]
  def index
    # ...
  end

  # 创建账目.
  # @raise [ActiveRecord::RecordInvalid]
  # @return [Object]
  def create
    # ...
  end

  def summary
    head 200
  end

  # TODO: 添加更多方法
end
  • summary 是增删改查之外的非标准方法
  • 运行 rspec spec/requests/api/v1/items_spec.rb:155 报错,提示需要实现 json 内容

修改 app/controllers/api/v1/items_controller.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Api::V1::ItemsController < ApplicationController
  # 分页查询账目.
  # @return [Object]
  def index
    # ...
  end

  # 创建账目.
  # @raise [ActiveRecord::RecordInvalid]
  # @return [Object]
  def create
    # ...
  end

  # 账目统计.
  # @return [Object]
  def summary
    current_user_id = request.env["current_user_id"]
    items = Item
      .where(user_id: current_user_id)
      .where(kind: params[:kind])
      .where({
        happened_at: params[:happened_at_after]..params[:happened_at_before]
      })
    hash = Hash.new
    items.each do |item|
      key = item
        .happened_at
        .in_time_zone("Beijing")
        .strftime("%Y-%m-%dT%H:%M:%S+08:00") # .strftime("%F") # .strftime("%Y-%m-%d")
      hash[key] ||= 0
      hash[key] += item.amount
    end
    groups = hash.map {
      |key, value| { "#{params[:group_by]}": key, "amount": value }
    }
    groups.sort! { |a, b| a[:happened_at] <=> b[:happened_at] }
    render json: {
      group: groups,
      total: {
        amount: items.sum(:amount)
      }
    }
  end

  # TODO: 添加更多方法
end
  • ``

参考


2. 按tag_id分组 ⇧

``


3. 更新API文档 ⇧

``


4. $3 ⇧

``


5. $3 ⇧

``


6. $3 ⇧

``


7. 可能的报错信息 ⇧

密钥相关报错

  • 拿到代码后,可能需要重新创建密钥:https://docs.qq.com/doc/DU3ByQXZWbFpQRHND 。
  • 这一步是可选的,但如果遇到 ActiveSupport::MessageEncryptor::InvalidMessage 报错,那么你就必须重新创建密钥了。

·未完待续·

参考文章

相关文章

  • 无

  • 作者: Joel
  • 文章链接:
  • 版权声明
  • 非自由转载-非商用-非衍生-保持署名