class WalletsController < ApplicationController before_action :require_login, except: :balance_chart def balance user = User.find_by_id(params[:id]) @wallet = user.get_wallet end def coin_changes user = User.find_by_id(params[:id]) @wallet = user.get_wallet if params[:category] == 'all' scope = CoinChange.where('to_wallet_id = ? OR from_wallet_id = ?', @wallet.id, @wallet.id) elsif params[:category] == 'income' # @coin_changes = CoinChange.where('to_wallet_id = ?', @wallet.id).limit(100) scope = @wallet.income elsif params[:category] == 'outcome' scope = @wallet.outcome end sort = params[:sort_by] || "created_at" sort_direction = params[:sort_direction] || "desc" scope = scope.reorder("#{sort} #{sort_direction}") unless scope.nil? @total = 0 @total = scope.length unless scope.nil? @coin_changes = kaminari_paginate(scope) unless scope.nil? end def balance_chart user = User.find_by_id(params[:id]) @wallet = user.get_wallet scope = CoinChange.where('to_wallet_id = ? OR from_wallet_id = ?', @wallet.id, @wallet.id) t1 = Time.now t2 = Time.new(t1.year, t1.month, t1.day-6) @balance_chart_data = scope.where('created_at > ? AND created_at < ?', t2, t1) @balance_chart_array = to_array(@balance_chart_data, @wallet.id) end private def to_array(data, id) t1 = Time.now start_time = Time.new(t1.year, t1.month, t1.day-6) end_time = Time.new(start_time.year, start_time.month, start_time.day+1) income = Array.new(7, 0) # 收入、支出 outcome = Array.new(7, 0) date = Array.new(7) date[0] = Time.new(start_time.year, start_time.month, start_time.day) index = 0 data.each do |i| until (i.created_at >= start_time) && (i.created_at < end_time) index += 1 start_time = end_time end_time = Time.new(start_time.year, start_time.month, start_time.day + 1) date[index] = Time.new(start_time.year, start_time.month, start_time.day) end if i.from_wallet_id == id outcome[index] += i.amount else income[index] += i.amount end end until end_time >= Time.now index += 1 start_time = end_time end_time = Time.new(start_time.year, start_time.month, start_time.day + 1) date[index] = Time.new(start_time.year, start_time.month, start_time.day) end Array[income, outcome, date] end end