Skip to content

Commit

Permalink
typescript: migrate cards from jsx to tsx (#3285)
Browse files Browse the repository at this point in the history
  • Loading branch information
MatissJanis authored Aug 19, 2024
1 parent d6afc85 commit db4b504
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 41 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import { Bar, BarChart, LabelList, ResponsiveContainer } from 'recharts';

Expand All @@ -18,15 +19,25 @@ import { ReportCard } from '../ReportCard';
import { simpleCashFlow } from '../spreadsheets/cash-flow-spreadsheet';
import { useReport } from '../useReport';

type CustomLabelProps = {
value?: number;
name: string;
position?: 'left' | 'right';
x?: number;
y?: number;
width?: number;
height?: number;
};

function CustomLabel({
value,
value = 0,
name,
position,
x,
y,
width: barWidth,
height: barHeight,
}) {
position = 'left',
x = 0,
y = 0,
width: barWidth = 0,
height: barHeight = 0,
}: CustomLabelProps) {
const valueLengthOffset = 20;

const yOffset = barHeight < 25 ? 105 : y;
Expand Down Expand Up @@ -68,16 +79,22 @@ function CustomLabel({
);
}

export function CashFlowCard({ isEditing, onRemove }) {
type CashFlowCardProps = {
isEditing?: boolean;
onRemove: () => void;
};

export function CashFlowCard({ isEditing, onRemove }: CashFlowCardProps) {
const { t } = useTranslation();
const end = monthUtils.currentDay();
const start = monthUtils.currentMonth() + '-01';

const params = useMemo(() => simpleCashFlow(start, end), [start, end]);
const data = useReport('cash_flow_simple', params);

const [isCardHovered, setIsCardHovered] = useState(false);
const onCardHover = useCallback(() => setIsCardHovered(true));
const onCardHoverEnd = useCallback(() => setIsCardHovered(false));
const onCardHover = useCallback(() => setIsCardHovered(true), []);
const onCardHoverEnd = useCallback(() => setIsCardHovered(false), []);

const { graphData } = data || {};
const expenses = -(graphData?.expense || 0);
Expand All @@ -90,7 +107,7 @@ export function CashFlowCard({ isEditing, onRemove }) {
menuItems={[
{
name: 'remove',
text: 'Remove',
text: t('Remove'),
},
]}
onMenuSelect={item => {
Expand Down Expand Up @@ -153,7 +170,7 @@ export function CashFlowCard({ isEditing, onRemove }) {
<LabelList
dataKey="income"
position="left"
content={<CustomLabel name="Income" />}
content={<CustomLabel name={t('Income')} />}
/>
</Bar>

Expand All @@ -165,7 +182,7 @@ export function CashFlowCard({ isEditing, onRemove }) {
<LabelList
dataKey="expenses"
position="right"
content={<CustomLabel name="Expenses" />}
content={<CustomLabel name={t('Expenses')} />}
/>
</Bar>
</BarChart>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import React, { useState, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import * as monthUtils from 'loot-core/src/shared/months';
import { integerToCurrency } from 'loot-core/src/shared/util';
import { type AccountEntity } from 'loot-core/src/types/models';

import { useResponsive } from '../../../ResponsiveProvider';
import { styles } from '../../../style';
Expand All @@ -16,14 +18,25 @@ import { ReportCard } from '../ReportCard';
import { createSpreadsheet as netWorthSpreadsheet } from '../spreadsheets/net-worth-spreadsheet';
import { useReport } from '../useReport';

export function NetWorthCard({ isEditing, accounts, onRemove }) {
type NetWorthCardProps = {
isEditing?: boolean;
accounts: AccountEntity[];
onRemove: () => void;
};

export function NetWorthCard({
isEditing,
accounts,
onRemove,
}: NetWorthCardProps) {
const { t } = useTranslation();
const { isNarrowWidth } = useResponsive();

const end = monthUtils.currentMonth();
const start = monthUtils.subMonths(end, 5);
const [isCardHovered, setIsCardHovered] = useState(false);
const onCardHover = useCallback(() => setIsCardHovered(true));
const onCardHoverEnd = useCallback(() => setIsCardHovered(false));
const onCardHover = useCallback(() => setIsCardHovered(true), []);
const onCardHoverEnd = useCallback(() => setIsCardHovered(false), []);

const params = useMemo(
() => netWorthSpreadsheet(start, end, accounts),
Expand All @@ -38,7 +51,7 @@ export function NetWorthCard({ isEditing, accounts, onRemove }) {
menuItems={[
{
name: 'remove',
text: 'Remove',
text: t('Remove'),
},
]}
onMenuSelect={item => {
Expand Down Expand Up @@ -88,8 +101,6 @@ export function NetWorthCard({ isEditing, accounts, onRemove }) {

{data ? (
<NetWorthGraph
start={start}
end={end}
graphData={data.graphData}
compact={true}
showTooltip={!isEditing && !isNarrowWidth}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useState, useMemo } from 'react';
import { Trans, useTranslation } from 'react-i18next';

import * as monthUtils from 'loot-core/src/shared/months';
import { amountToCurrency } from 'loot-core/src/shared/util';
Expand All @@ -25,6 +26,8 @@ type SpendingCardProps = {
};

export function SpendingCard({ isEditing, onRemove }: SpendingCardProps) {
const { t } = useTranslation();

const [isCardHovered, setIsCardHovered] = useState(false);
const [spendingReportFilter = ''] = useLocalPref('spendingReportFilter');
const [spendingReportTime = 'lastMonth'] = useLocalPref('spendingReportTime');
Expand Down Expand Up @@ -59,7 +62,9 @@ export function SpendingCard({ isEditing, onRemove }: SpendingCardProps) {
if (!spendingReportFeatureFlag) {
return (
<MissingReportCard isEditing={isEditing} onRemove={onRemove}>
The experimental spending report feature has not been enabled.
<Trans>
The experimental spending report feature has not been enabled.
</Trans>
</MissingReportCard>
);
}
Expand All @@ -71,7 +76,7 @@ export function SpendingCard({ isEditing, onRemove }: SpendingCardProps) {
menuItems={[
{
name: 'remove',
text: 'Remove',
text: t('Remove'),
},
]}
onMenuSelect={item => {
Expand Down Expand Up @@ -128,7 +133,7 @@ export function SpendingCard({ isEditing, onRemove }: SpendingCardProps) {
{!showLastMonth ? (
<View style={{ padding: 5 }}>
<p style={{ margin: 0, textAlign: 'center' }}>
Additional data required to generate graph
<Trans>Additional data required to generate graph</Trans>
</p>
</View>
) : data ? (
Expand All @@ -140,7 +145,7 @@ export function SpendingCard({ isEditing, onRemove }: SpendingCardProps) {
compare={spendingReportCompare}
/>
) : (
<LoadingIndicator message="Loading report..." />
<LoadingIndicator message={t('Loading report...')} />
)}
</View>
</ReportCard>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @ts-strict-ignore
import React from 'react';

import * as d from 'date-fns';
Expand All @@ -13,8 +12,11 @@ import { type RuleConditionEntity } from 'loot-core/types/models';
import { AlignedText } from '../../common/AlignedText';
import { runAll, indexCashFlow } from '../util';

export function simpleCashFlow(start, end) {
return async (spreadsheet, setData) => {
export function simpleCashFlow(start: string, end: string) {
return async (
spreadsheet: ReturnType<typeof useSpreadsheet>,
setData: (data: { graphData: { income: number; expense: number } }) => void,
) => {
function makeQuery() {
return q('transactions')
.filter({
Expand Down Expand Up @@ -109,7 +111,16 @@ export function cashFlowByDate(
};
}

function recalculate(data, start, end, isConcise) {
function recalculate(
data: [
number,
Array<{ date: string; isTransfer: string | null; amount: number }>,
Array<{ date: string; isTransfer: string | null; amount: number }>,
],
start: string,
end: string,
isConcise: boolean,
) {
const [startingBalance, income, expense] = data;
const convIncome = income.map(t => {
return { ...t, isTransfer: t.isTransfer !== null };
Expand All @@ -123,15 +134,25 @@ function recalculate(data, start, end, isConcise) {
monthUtils.getMonth(end),
)
: monthUtils.dayRangeInclusive(start, end);
const incomes = indexCashFlow(convIncome, 'date', 'isTransfer');
const expenses = indexCashFlow(convExpense, 'date', 'isTransfer');
const incomes = indexCashFlow(convIncome);
const expenses = indexCashFlow(convExpense);

let balance = startingBalance;
let totalExpenses = 0;
let totalIncome = 0;
let totalTransfers = 0;

const graphData = dates.reduce(
const graphData = dates.reduce<{
expenses: Array<{ x: Date; y: number }>;
income: Array<{ x: Date; y: number }>;
transfers: Array<{ x: Date; y: number }>;
balances: Array<{
x: Date;
y: number;
premadeLabel: JSX.Element;
amount: number;
}>;
}>(
(res, date) => {
let income = 0;
let expense = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export function createSpreadsheet(
end: string,
accounts: AccountEntity[],
conditions: RuleConditionEntity[] = [],
conditionsOp: 'and' | 'or',
conditionsOp: 'and' | 'or' = 'and',
) {
return async (
spreadsheet: ReturnType<typeof useSpreadsheet>,
Expand Down
14 changes: 5 additions & 9 deletions packages/desktop-client/src/components/reports/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,12 @@ export async function runAll(

export function indexCashFlow<
T extends { date: string; isTransfer: boolean; amount: number },
>(data: T[], date: string, isTransfer: string) {
const results = {};
>(data: T[]): Record<string, Record<'true' | 'false', number>> {
const results: Record<string, Record<'true' | 'false', number>> = {};
data.forEach(item => {
const findExisting = results[item.date]
? results[item.date][item.isTransfer]
? results[item.date][item.isTransfer]
: 0
: 0;
const result = { [item[isTransfer]]: item.amount + findExisting };
results[item[date]] = { ...results[item[date]], ...result };
const findExisting = results?.[item.date]?.[String(item.isTransfer)] ?? 0;
const result = { [String(item.isTransfer)]: item.amount + findExisting };
results[item.date] = { ...results[item.date], ...result };
});
return results;
}
3 changes: 2 additions & 1 deletion packages/loot-core/src/types/server-handlers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
PayeeEntity,
} from './models';
import { GlobalPrefs, LocalPrefs } from './prefs';
import { Query } from './query';
import { EmptyObject } from './util';

export interface ServerHandlers {
Expand Down Expand Up @@ -137,7 +138,7 @@ export interface ServerHandlers {

'create-query': (arg: { sheetName; name; query }) => Promise<unknown>;

query: (query) => Promise<{ data; dependencies }>;
query: (query: Query) => Promise<{ data: unknown; dependencies }>;

'account-update': (arg: { id; name }) => Promise<unknown>;

Expand Down
6 changes: 6 additions & 0 deletions upcoming-release-notes/3285.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
category: Maintenance
authors: [Matissjanis]
---

TypeScript: migrate report cards to TS.

0 comments on commit db4b504

Please sign in to comment.