Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add net balance report to reports controller #47

Merged
merged 2 commits into from
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions app/controllers/api/report_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

module Api
class ReportController < ApplicationController
before_action :set_data_range, only: [:income_vs_expense, :eod_balance, :category, :subcategory]
before_action :set_data_range, only: [:income_vs_expense, :eod_balance, :net_balance, :category, :subcategory]

def index; end

Expand All @@ -31,7 +31,7 @@ def income_expense_bar
render json: { report: report_data }
end

# balance
# eod_balance
# retrieves the end of day balance for the specified account for the date range
def eod_balance
if account.nil?
Expand All @@ -44,6 +44,13 @@ def eod_balance
render json: { report: @line_chart_data, account_id: account&.id }
end

# net_balance
# retrieves the end of day balance for ALL accounts for the date range
def net_balance
search = Lib::NetBalanceSearch.new(date_range: @date_range)
render json: { report: search.eod_balance }
end

def category
set_category
search = Lib::CategorySearch.new(category: @category, date_range: @date_range)
Expand Down
2 changes: 2 additions & 0 deletions app/javascript/components/MyMoney.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import SubcategoryReport from './reports/SubcategoryReport'
import IncomeExpenseBarChart from './reports/IncomeExpenseBarChart'
import IncomeVsExpensesReport from './reports/IncomeVsExpensesReport'
import LoanReport from './loan/LoanReport'
import NetBalanceChart from './reports/NetBalanceChart'
import store from '../stores/store'

const MyMoney = () => {
Expand All @@ -37,6 +38,7 @@ const MyMoney = () => {
path="/reports/accountBalance"
element={<AccountBalanceChart />}
/>
<Route path="/reports/netBalance" element={<NetBalanceChart />} />
<Route
path="/reports/incomeVsExpenseBar"
element={<IncomeExpenseBarChart />}
Expand Down
5 changes: 3 additions & 2 deletions app/javascript/components/common/controls/MultiSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export type Option = {
name: string

// allow any extra attributes we don't care about here
[key: string]: unknown;
[key: string]: unknown
}

export type SingleOption = SingleValue<Option>
Expand All @@ -19,12 +19,13 @@ type MultiSelectProps = {
value: Option | Option[] | undefined
options?: Option[]
groupedOptions?: GroupBase<Option>[]
onChange: (newValue: MultiOption | SingleOption | null ) => void
onChange: (newValue: MultiOption | SingleOption | null) => void
}

const MultiSelect = (props: MultiSelectProps) => {
return (
<Select
inputId={props.name}
value={props.value || null}
getOptionLabel={(option: Option) => option.name}
getOptionValue={(option: Option) => option.id.toString()}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const DateRangeFilter = () => {
return (
<div className="date-range-filter">
<div className="form-group">
<label htmlFor="dateRangeSelect" className="control-label">
<label htmlFor="dateRangeId" className="control-label">
Dates
</label>
<Select
Expand Down
39 changes: 27 additions & 12 deletions app/javascript/components/layout/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,30 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { LinkContainer } from 'react-router-bootstrap';
import { Navbar, Nav, NavDropdown } from 'react-bootstrap';
import React from 'react'
import { Link } from 'react-router-dom'
import { LinkContainer } from 'react-router-bootstrap'
import { Navbar, Nav, NavDropdown } from 'react-bootstrap'

import '../../stylesheets/nav.scss';
import '../../stylesheets/nav.scss'

const Header = () => (
<Navbar>
<Navbar.Brand><Link to="/"><strong>my</strong> money</Link></Navbar.Brand>
<Navbar.Brand>
<Link to="/">
<strong>my</strong> money
</Link>
</Navbar.Brand>
<Nav>
<LinkContainer to="/accounts"><Nav.Link>accounts</Nav.Link></LinkContainer>
<LinkContainer to="/transactions"><Nav.Link>transactions</Nav.Link></LinkContainer>
<LinkContainer to="/categories"><Nav.Link>categories</Nav.Link></LinkContainer>
<LinkContainer to="/patterns"><Nav.Link>patterns</Nav.Link></LinkContainer>
<LinkContainer to="/accounts">
<Nav.Link>accounts</Nav.Link>
</LinkContainer>
<LinkContainer to="/transactions">
<Nav.Link>transactions</Nav.Link>
</LinkContainer>
<LinkContainer to="/categories">
<Nav.Link>categories</Nav.Link>
</LinkContainer>
<LinkContainer to="/patterns">
<Nav.Link>patterns</Nav.Link>
</LinkContainer>
<NavDropdown title="reports" id="basic-nav-dropdown">
<LinkContainer to="/reports/incomeVsExpenses">
<NavDropdown.Item>Income vs Expenses</NavDropdown.Item>
Expand All @@ -30,9 +42,12 @@ const Header = () => (
<LinkContainer to="/reports/accountBalance">
<NavDropdown.Item>Account Balance Line Chart</NavDropdown.Item>
</LinkContainer>
<LinkContainer to="/reports/netBalance">
<NavDropdown.Item>Net Balance Chart</NavDropdown.Item>
</LinkContainer>
</NavDropdown>
</Nav>
</Navbar>
);
)

export default Header;
export default Header
7 changes: 6 additions & 1 deletion app/javascript/components/reports/D3LineChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,12 @@ const D3LineChart = (props: D3LineChartProps) => {
<div className="chart-container">
<ChartTooltip show={showTooltip} tooltipData={tooltipData} />
<ChartLegend seriesData={props.seriesData} />
<svg width="100%" height={`${chartOptions.height}px`} ref={ref} />
<svg
data-testid="d3-line-chart"
width="100%"
height={`${chartOptions.height}px`}
ref={ref}
/>
</div>
)
}
Expand Down
40 changes: 40 additions & 0 deletions app/javascript/components/reports/NetBalanceChart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import React from 'react'

import PageHeader from '../common/PageHeader'
import SearchCriteria, {
DATE_RANGE_FILTER,
} from '../common/criteria/SearchCriteria'
import D3LineChart from './D3LineChart'
import { useGetNetBalanceReportQuery } from 'stores/reportApi'
import { UseCurrentDateRange } from 'hooks/useCurrentDateRange'
import { transformNetBalanceReport } from 'transformers/reportTransformer'

import '../../stylesheets/common.scss'
import '../../stylesheets/report.scss'

const NetBalanceChart = () => {
const { currentDateRange } = UseCurrentDateRange()
const { data, isLoading } = useGetNetBalanceReportQuery(currentDateRange, {
skip: !currentDateRange,
})

const renderChart = () => {
if (data) {
const seriesData = transformNetBalanceReport(data)
return <D3LineChart seriesData={[seriesData]} />
}
return undefined
}

return (
<div>
<PageHeader title="Net Balance Report" isLoading={isLoading} />
<SearchCriteria filters={[{ name: DATE_RANGE_FILTER }]} />
<div id="report" className="container">
{renderChart()}
</div>
</div>
)
}

export default NetBalanceChart
1 change: 1 addition & 0 deletions app/javascript/stores/applicationApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const applicationApi = createApi({
'patterns',
'loan-report',
'matching-transactions',
'net-balance-report',
'subcategories',
'subcategory-report',
'transactions',
Expand Down
12 changes: 12 additions & 0 deletions app/javascript/stores/reportApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
DoublePointResponse,
LineSeriesData,
LoanReportResponse,
PointResponse,
TransactionReport,
} from 'types/models'
import {
Expand Down Expand Up @@ -121,6 +122,16 @@ export const reportApi = applicationApi.injectEndpoints({
return { data }
},
}),
getNetBalanceReport: builder.query<PointResponse[], DateRange | undefined>({
query(dateRange) {
return {
url: `report/net_balance?from_date=${dateRange?.fromDate}&to_date=${dateRange?.toDate}`,
}
},
transformResponse: (response: { report: PointResponse[] }) =>
response.report,
providesTags: () => ['net-balance-report'],
}),
}),
})

Expand All @@ -131,4 +142,5 @@ export const {
useGetCategoryReportQuery,
useGetSubcategoryReportQuery,
useGetAccountBalanceReportQuery,
useGetNetBalanceReportQuery,
} = reportApi
12 changes: 12 additions & 0 deletions app/javascript/transformers/reportTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,15 @@ export const chartDataForCombo = (
],
}
}

export const transformNetBalanceReport = (report: PointResponse[]): LineSeriesData => {
const data: Point[] = report.map((data) => [
new Date(data[0]),
centsToDollars(data[1]),
])
return {
name: 'Net balance',
data,
backgroundColour: '#66CC66'
}
}
72 changes: 72 additions & 0 deletions app/models/lib/net_balance_search.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# frozen_string_literal: true

module Lib
# NetBalance
#
# This search retrieves the end of day balances for all accounts for the
# specified date range.
class NetBalanceSearch < Search
attr_reader :date_range

LINE_CHART_DF = '%d %b, %Y'

def initialize(attrs)
super()
@date_range = attrs.fetch(:date_range, Lib::CurrentMonthDateRange.new)
end

# returns an array of end of day balances with the following format:
# ["01-Jan-14", 56].
def eod_balance
sql_data = transactions.to_a.group_by(&:date).sort
build_data(sql_data)
end

private

def transaction_query
Transaction.search_by_date(@date_range).date_order
end

# Only need date and eod balance
def build_data(sql_data)
data = []
add_first_day(sql_data, data)
format_data(sql_data, data)
add_last_day(sql_data, data)
data
end

def format_data(sql_data, data)
balance = data.first&.last || total_eod_balance(sql_data.first.first - 1.day)

sql_data.each do |date, ts|
balance += ts.sum(&:amount)
data << [date.strftime(LINE_CHART_DF), balance]
end
end

# if first day of date range not in data, then add it
def add_first_day(sql_data, data)
first_day = @date_range.from_date
return if sql_data.first && (sql_data.first.first == first_day)

data.unshift([first_day.strftime(LINE_CHART_DF), total_eod_balance(first_day)])
end

def total_eod_balance(date)
eod_balance = 0
Account.find_each do |a|
eod_balance += a.eod_balance(date).to_i
end
eod_balance
end

# if last day of date range not in data, then add it
def add_last_day(sql_data, data)
return if sql_data.last && (sql_data.last.first == @date_range.to_date)

data << [@date_range.to_date.strftime(LINE_CHART_DF), data.last[1]]
end
end
end
1 change: 1 addition & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
get 'report/subcategory'
get 'report/category'
get 'report/eod_balance'
get 'report/net_balance'
get 'report/home_loan'
get 'report/index'
end
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"jsdom": "23.2.0",
"msw": "^2.4.9",
"prettier": "^3.3.3",
"react-select-event": "^5.5.1",
"sass": "^1.74.1",
"ts-jest": "^29.2.5",
"vite": "^5.2.10",
Expand Down
22 changes: 22 additions & 0 deletions spec/controllers/api/report_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,28 @@
end
end

describe 'Net Balance Report' do
it 'returns an array of eod balances across all accounts' do
from_date = '2014-01-01'
to_date = '2014-01-2'
data = [['01 Jan, 2014', 4.0], ['02 Jan, 2014', 14.0]]

search = instance_double Lib::NetBalanceSearch
date_range = instance_double Lib::CustomDateRange

allow(Lib::CustomDateRange).to receive(:new).with(from_date:, to_date:).and_return(date_range)
allow(Lib::NetBalanceSearch).to receive(:new).with(date_range:).and_return(search)
allow(search).to receive(:eod_balance).and_return(data)

get :net_balance, params: { from_date:, to_date: }

expect(response).to have_http_status(:ok)
json = response.parsed_body
expect(json['report'].length).to eq(2)
expect(json['report']).to eq(data)
end
end

describe 'Income vs Expense Bar Chart' do
it 'returns an array of monthly income and expenses' do
income_data = [['date1', 40], ['date2', 140]]
Expand Down
1 change: 0 additions & 1 deletion spec/factories/transaction.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
amount { 555 }
fitid { 'This is a fitid' }
transaction_type { 'bank_transaction' }
bank_statement
account { FactoryBot.create(:account) }
end

Expand Down
Loading