Skip to content

A local-first personal finance app

[TS migration] MobileBudget tsx (#2081)

Joel Jeremy Marquez8bf0f8e5bf46
diff --git a/packages/desktop-client/src/components/SyncRefresh.ts b/packages/desktop-client/src/components/SyncRefresh.tsx
similarity index 76%
rename from packages/desktop-client/src/components/SyncRefresh.ts
rename to packages/desktop-client/src/components/SyncRefresh.tsx
index 010f78e7e4..adfcd8f4b7 100644
--- a/packages/desktop-client/src/components/SyncRefresh.ts
+++ b/packages/desktop-client/src/components/SyncRefresh.tsx
@@ -1,4 +1,4 @@
-import { type ReactNode, useState } from 'react';
+import React, { type ReactNode, useState } from 'react';
type ChildrenProps = {
refreshing: boolean;
@@ -17,5 +17,5 @@ export function SyncRefresh({ onSync, children }: SyncRefreshProps) {
setSyncing(false);
}
- return children({ refreshing: syncing, onRefresh: onSync_ });
+ return <>{children({ refreshing: syncing, onRefresh: onSync_ })}</>;
}
diff --git a/packages/desktop-client/src/components/budget/MobileBudget.jsx b/packages/desktop-client/src/components/budget/MobileBudget.jsx
deleted file mode 100644
index a6821f7c75..0000000000
--- a/packages/desktop-client/src/components/budget/MobileBudget.jsx
+++ /dev/null
@@ -1,479 +0,0 @@
-import React, { Component } from 'react';
-import { useSelector } from 'react-redux';
-
-import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';
-import { send, listen } from 'loot-core/src/platform/client/fetch';
-import * as monthUtils from 'loot-core/src/shared/months';
-
-import { useActions } from '../../hooks/useActions';
-import { useCategories } from '../../hooks/useCategories';
-import { useSetThemeColor } from '../../hooks/useSetThemeColor';
-import { AnimatedLoading } from '../../icons/AnimatedLoading';
-import { theme } from '../../style';
-import { View } from '../common/View';
-import { SyncRefresh } from '../SyncRefresh';
-
-import { BudgetTable } from './MobileBudgetTable';
-import { prewarmMonth, switchBudgetType } from './util';
-
-const CATEGORY_BUDGET_EDIT_ACTION = 'category-budget';
-const BALANCE_MENU_OPEN_ACTION = 'balance-menu';
-
-class BudgetInner extends Component {
- constructor(props) {
- super(props);
-
- const currentMonth = monthUtils.currentMonth();
- this.state = {
- bounds: { start: currentMonth, end: currentMonth },
- currentMonth,
- initialized: false,
- editMode: false,
- editingBudgetCategoryId: null,
- openBalanceActionMenuId: null,
- };
- }
-
- async loadCategories() {
- await this.props.getCategories();
- }
-
- async componentDidMount() {
- // let removeBlur = this.props.navigation.addListener('didBlur', () => {
- // this.setState({ editMode: false });
- // });
-
- const { start, end } = await send('get-budget-bounds');
- await prewarmMonth(
- this.props.budgetType,
- this.props.spreadsheet,
- this.state.currentMonth,
- );
-
- this.setState({
- bounds: { start, end },
- initialized: true,
- });
-
- const unlisten = listen('sync-event', ({ type, tables }) => {
- if (
- type === 'success' &&
- (tables.includes('categories') ||
- tables.includes('category_mapping') ||
- tables.includes('category_groups'))
- ) {
- // TODO: is this loading every time?
- this.loadCategories();
- }
- });
-
- this.cleanup = () => {
- // removeBlur();
- unlisten();
- };
- }
-
- componentWillUnmount() {
- this.cleanup?.();
- }
-
- onShowBudgetSummary = () => {
- if (this.props.budgetType === 'report') {
- this.props.pushModal('report-budget-summary', {
- month: this.state.currentMonth,
- });
- } else {
- this.props.pushModal('rollover-budget-summary', {
- month: this.state.currentMonth,
- onBudgetAction: this.props.applyBudgetAction,
- });
- }
- };
-
- onBudgetAction = type => {
- const { currentMonth } = this.state;
- this.props.applyBudgetAction(currentMonth, type, this.state.bounds);
- };
-
- onAddGroup = () => {
- this.props.pushModal('new-category-group', {
- onValidate: name => (!name ? 'Name is required.' : null),
- onSubmit: async name => {
- await this.props.createGroup(name);
- },
- });
- };
-
- onAddCategory = (groupId, isIncome) => {
- this.props.pushModal('new-category', {
- onValidate: name => (!name ? 'Name is required.' : null),
- onSubmit: async name => {
- this.props.collapseModals('category-group-menu');
- await this.props.createCategory(name, groupId, isIncome);
- },
- });
- };
-
- onSaveGroup = group => {
- this.props.updateGroup(group);
- };
-
- onDeleteGroup = async groupId => {
- const { categoryGroups } = this.props;
- const group = categoryGroups?.find(g => g.id === groupId);
-
- if (!group) {
- return;
- }
-
- let mustTransfer = false;
- for (const category of group.categories) {
- if (await send('must-category-transfer', { id: category.id })) {
- mustTransfer = true;
- break;
- }
- }
-
- if (mustTransfer) {
- this.props.pushModal('confirm-category-delete', {
- group: groupId,
- onDelete: transferCategory => {
- this.props.collapseModals('category-group-menu');
- this.props.deleteGroup(groupId, transferCategory);
- },
- });
- } else {
- this.props.collapseModals('category-group-menu');
- this.props.deleteGroup(groupId);
- }
- };
-
- onSaveCategory = category => {
- this.props.updateCategory(category);
- };
-
- onDeleteCategory = async categoryId => {
- const mustTransfer = await send('must-category-transfer', {
- id: categoryId,
- });
-
- if (mustTransfer) {
- this.props.pushModal('confirm-category-delete', {
- category: categoryId,
- onDelete: transferCategory => {
- if (categoryId !== transferCategory) {
- this.props.collapseModals('category-menu');
- this.props.deleteCategory(categoryId, transferCategory);
- }
- },
- });
- } else {
- this.props.collapseModals('category-menu');
- this.props.deleteCategory(categoryId);
- }
- };
-
- onReorderCategory = (id, { inGroup, aroundCategory }) => {
- const { categoryGroups } = this.props;
- let groupId, targetId;
-
- if (inGroup) {
- groupId = inGroup;
- } else if (aroundCategory) {
- const { id: originalCatId, position } = aroundCategory;
-
- let catId = originalCatId;
- const group = categoryGroups.find(group =>
- group.categories.find(cat => cat.id === catId),
- );
-
- if (position === 'bottom') {
- const { categories } = group;
- const idx = categories.findIndex(cat => cat.id === catId);
- catId = idx < categories.length - 1 ? categories[idx + 1].id : null;
- }
-
- groupId = group.id;
- targetId = catId;
- }
-
- this.props.moveCategory(id, groupId, targetId);
- };
-
- onReorderGroup = (id, targetId, position) => {
- const { categoryGroups } = this.props;
-
- if (position === 'bottom') {
- const idx = categoryGroups.findIndex(group => group.id === targetId);
- targetId =
- idx < categoryGroups.length - 1 ? categoryGroups[idx + 1].id : null;
- }
-
- this.props.moveCategoryGroup(id, targetId);
- };
-
- sync = async () => {
- const { updated, error } = await this.props.sync();
- if (error) {
- return 'error';
- } else if (updated) {
- return 'updated';
- }
- return null;
- };
-
- onPrevMonth = async () => {
- const { spreadsheet, budgetType } = this.props;
- const month = monthUtils.subMonths(this.state.currentMonth, 1);
- await prewarmMonth(budgetType, spreadsheet, month);
- this.setState({ currentMonth: month, initialized: true });
- };
-
- onNextMonth = async () => {
- const { spreadsheet, budgetType } = this.props;
- const month = monthUtils.addMonths(this.state.currentMonth, 1);
- await prewarmMonth(budgetType, spreadsheet, month);
- this.setState({ currentMonth: month, initialized: true });
- };
-
- onOpenMonthActionMenu = () => {
- const { budgetType } = this.props;
-
- const options = [
- 'Copy last month’s budget',
- 'Set budgets to zero',
- 'Set budgets to 3 month average',
- budgetType === 'report' && 'Apply to all future budgets',
- ].filter(Boolean);
-
- this.props.showActionSheetWithOptions(
- {
- options,
- cancelButtonIndex: options.length - 1,
- title: 'Actions',
- },
- idx => {
- switch (idx) {
- case 0:
- this.setState({ editMode: true });
- break;
- case 1:
- this.onBudgetAction('copy-last');
- break;
- case 2:
- this.onBudgetAction('set-zero');
- break;
- case 3:
- this.onBudgetAction('set-3-avg');
- break;
- case 4:
- if (budgetType === 'report') {
- this.onBudgetAction('set-all-future');
- }
- break;
- default:
- }
- },
- );
- };
-
- onSwitchBudgetType = async () => {
- const { spreadsheet, budgetType, loadPrefs } = this.props;
- const { bounds, currentMonth } = this.state;
-
- this.setState({ initialized: false });
-
- const newBudgetType = budgetType === 'rollover' ? 'report' : 'rollover';
- await switchBudgetType(
- newBudgetType,
- spreadsheet,
- bounds,
- currentMonth,
- () => loadPrefs(),
- );
-
- this.setState({ initialized: true });
- };
-
- onSaveNotes = async (id, notes) => {
- await send('notes-save', { id, note: notes });
- };
-
- onEditGroupNotes = id => {
- const { categoryGroups } = this.props;
- const group = categoryGroups.find(g => g.id === id);
- this.props.pushModal('notes', {
- id,
- name: group.name,
- onSave: this.onSaveNotes,
- });
- };
-
- onEditCategoryNotes = id => {
- const { categories } = this.props;
- const category = categories.find(c => c.id === id);
- this.props.pushModal('notes', {
- id,
- name: category.name,
- onSave: this.onSaveNotes,
- });
- };
-
- onEditGroup = id => {
- const { categoryGroups } = this.props;
- const group = categoryGroups.find(g => g.id === id);
- this.props.pushModal('category-group-menu', {
- groupId: group.id,
- onSave: this.onSaveGroup,
- onAddCategory: this.onAddCategory,
- onEditNotes: this.onEditGroupNotes,
- onDelete: this.onDeleteGroup,
- });
- };
-
- onEditCategory = id => {
- const { categories } = this.props;
- const category = categories.find(c => c.id === id);
- this.props.pushModal('category-menu', {
- categoryId: category.id,
- onSave: this.onSaveCategory,
- onEditNotes: this.onEditCategoryNotes,
- onDelete: this.onDeleteCategory,
- });
- };
-
- onEditCategoryBudget = id => {
- this.onEdit(CATEGORY_BUDGET_EDIT_ACTION, id);
- };
-
- onOpenBalanceActionMenu = id => {
- this.onEdit(BALANCE_MENU_OPEN_ACTION, id);
- };
-
- onEdit = (action, id) => {
- const { editingBudgetCategoryId, openBalanceActionMenuId } = this.state;
-
- // Do not allow editing if another field is currently being edited.
- // Cancel the currently editing field in that case.
- const currentlyEditing = editingBudgetCategoryId || openBalanceActionMenuId;
-
- this.setState({
- editingBudgetCategoryId:
- action === CATEGORY_BUDGET_EDIT_ACTION && !currentlyEditing ? id : null,
- openBalanceActionMenuId:
- action === BALANCE_MENU_OPEN_ACTION && !currentlyEditing ? id : null,
- });
-
- return { action, editingId: !currentlyEditing ? id : null };
- };
-
- render() {
- const {
- currentMonth,
- bounds,
- editMode,
- initialized,
- editingBudgetCategoryId,
- openBalanceActionMenuId,
- } = this.state;
- const {
- categoryGroups,
- categories,
- prefs,
- savePrefs,
- budgetType,
- navigation,
- applyBudgetAction,
- pushModal,
- } = this.props;
- const numberFormat = prefs.numberFormat || 'comma-dot';
- const hideFraction = prefs.hideFraction || false;
-
- if (!categoryGroups || !initialized) {
- return (
- <View
- style={{
- flex: 1,
- backgroundColor: theme.mobilePageBackground,
- alignItems: 'center',
- justifyContent: 'center',
- marginBottom: 25,
- }}
- >
- <AnimatedLoading width={25} height={25} />
- </View>
- );
- }
-
- return (
- <SyncRefresh onSync={this.sync}>
- {({ refreshing, onRefresh }) => (
- <BudgetTable
- // This key forces the whole table rerender when the number
- // format changes
- key={numberFormat + hideFraction}
- categoryGroups={categoryGroups}
- categories={categories}
- type={budgetType}
- month={currentMonth}
- monthBounds={bounds}
- navigation={navigation}
- // refreshControl={
- // <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
- // }
- editMode={editMode}
- onEditMode={flag => this.setState({ editMode: flag })}
- onShowBudgetSummary={this.onShowBudgetSummary}
- onPrevMonth={this.onPrevMonth}
- onNextMonth={this.onNextMonth}
- onSaveGroup={this.onSaveGroup}
- onDeleteGroup={this.onDeleteGroup}
- onAddGroup={this.onAddGroup}
- onAddCategory={this.onAddCategory}
- onSaveCategory={this.onSaveCategory}
- onDeleteCategory={this.onDeleteCategory}
- onReorderCategory={this.onReorderCategory}
- onReorderGroup={this.onReorderGroup}
- onOpenMonthActionMenu={this.onOpenMonthActionMenu}
- onBudgetAction={applyBudgetAction}
- onRefresh={onRefresh}
- onSwitchBudgetType={this.onSwitchBudgetType}
- onSaveNotes={this.onSaveNotes}
- onEditGroupNotes={this.onEditGroupNotes}
- onEditCategoryNotes={this.onEditCategoryNotes}
- savePrefs={savePrefs}
- pushModal={pushModal}
- onEditGroup={this.onEditGroup}
- onEditCategory={this.onEditCategory}
- editingBudgetCategoryId={editingBudgetCategoryId}
- onEditCategoryBudget={this.onEditCategoryBudget}
- openBalanceActionMenuId={openBalanceActionMenuId}
- onOpenBalanceActionMenu={this.onOpenBalanceActionMenu}
- />
- )}
- </SyncRefresh>
- );
- }
-}
-
-export function Budget() {
- const { list: categories, grouped: categoryGroups } = useCategories();
- const budgetType = useSelector(
- state => state.prefs.local.budgetType || 'rollover',
- );
- const prefs = useSelector(state => state.prefs.local);
-
- const actions = useActions();
- const spreadsheet = useSpreadsheet();
- useSetThemeColor(theme.mobileViewTheme);
- return (
- <BudgetInner
- categoryGroups={categoryGroups}
- categories={categories}
- budgetType={budgetType}
- prefs={prefs}
- {...actions}
- spreadsheet={spreadsheet}
- />
- );
-}
diff --git a/packages/desktop-client/src/components/budget/MobileBudget.tsx b/packages/desktop-client/src/components/budget/MobileBudget.tsx
new file mode 100644
index 0000000000..415652629b
--- /dev/null
+++ b/packages/desktop-client/src/components/budget/MobileBudget.tsx
@@ -0,0 +1,477 @@
+import React, { useEffect, useState } from 'react';
+import { useSelector } from 'react-redux';
+
+import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';
+import { type PrefsState } from 'loot-core/src/client/state-types/prefs';
+import { send, listen } from 'loot-core/src/platform/client/fetch';
+import * as monthUtils from 'loot-core/src/shared/months';
+import {
+ type CategoryEntity,
+ type CategoryGroupEntity,
+} from 'loot-core/src/types/models';
+
+import { type BoundActions, useActions } from '../../hooks/useActions';
+import { useCategories } from '../../hooks/useCategories';
+import { useSetThemeColor } from '../../hooks/useSetThemeColor';
+import { AnimatedLoading } from '../../icons/AnimatedLoading';
+import { theme } from '../../style';
+import { View } from '../common/View';
+import { SyncRefresh } from '../SyncRefresh';
+
+import { BudgetTable } from './MobileBudgetTable';
+import { prewarmMonth, switchBudgetType } from './util';
+
+const CATEGORY_BUDGET_EDIT_ACTION = 'category-budget';
+const BALANCE_MENU_OPEN_ACTION = 'balance-menu';
+
+type BudgetInnerProps = {
+ categories: CategoryEntity[];
+ categoryGroups: CategoryGroupEntity[];
+ prefs: PrefsState['local'];
+ loadPrefs: BoundActions['loadPrefs'];
+ savePrefs: BoundActions['savePrefs'];
+ budgetType: 'rollover' | 'report';
+ spreadsheet: ReturnType<typeof useSpreadsheet>;
+ applyBudgetAction: BoundActions['applyBudgetAction'];
+ collapseModals: BoundActions['collapseModals'];
+ pushModal: BoundActions['pushModal'];
+ getCategories: BoundActions['getCategories'];
+ createCategory: BoundActions['createCategory'];
+ updateCategory: BoundActions['updateCategory'];
+ deleteCategory: BoundActions['deleteCategory'];
+ moveCategory: BoundActions['moveCategory'];
+ createGroup: BoundActions['createGroup'];
+ updateGroup: BoundActions['updateGroup'];
+ deleteGroup: BoundActions['deleteGroup'];
+ moveCategoryGroup: BoundActions['moveCategoryGroup'];
+ sync: BoundActions['sync'];
+};
+
+function BudgetInner(props: BudgetInnerProps) {
+ const {
+ categoryGroups,
+ categories,
+ prefs,
+ loadPrefs,
+ savePrefs,
+ budgetType,
+ spreadsheet,
+ applyBudgetAction,
+ collapseModals,
+ pushModal,
+ createGroup,
+ updateGroup,
+ deleteGroup,
+ moveCategoryGroup,
+ createCategory,
+ updateCategory,
+ deleteCategory,
+ moveCategory,
+ } = props;
+
+ const currMonth = monthUtils.currentMonth();
+
+ const [bounds, setBounds] = useState({ start: currMonth, end: currMonth });
+ const [currentMonth, setCurrentMonth] = useState(currMonth);
+ const [initialized, setInitialized] = useState(false);
+ const [editMode, setEditMode] = useState(false);
+ const [editingBudgetCategoryId, setEditingBudgetCategoryId] = useState(null);
+ const [openBalanceActionMenuId, setOpenBalanceActionMenuId] = useState(null);
+
+ useEffect(() => {
+ async function init() {
+ const { start, end } = await send('get-budget-bounds');
+ setBounds({ start, end });
+
+ await prewarmMonth(props.budgetType, props.spreadsheet, currentMonth);
+
+ setInitialized(true);
+ }
+
+ init();
+
+ const unlisten = listen('sync-event', ({ type, tables }) => {
+ if (
+ type === 'success' &&
+ (tables.includes('categories') ||
+ tables.includes('category_mapping') ||
+ tables.includes('category_groups'))
+ ) {
+ // TODO: is this loading every time?
+ props.getCategories();
+ }
+ });
+
+ return () => unlisten();
+ }, []);
+
+ const onShowBudgetSummary = () => {
+ if (budgetType === 'report') {
+ pushModal('report-budget-summary', {
+ month: currentMonth,
+ });
+ } else {
+ pushModal('rollover-budget-summary', {
+ month: currentMonth,
+ onBudgetAction: applyBudgetAction,
+ });
+ }
+ };
+
+ // const onBudgetAction = type => {
+ // applyBudgetAction(currentMonth, type, bounds);
+ // };
+
+ const onAddGroup = () => {
+ pushModal('new-category-group', {
+ onValidate: name => (!name ? 'Name is required.' : null),
+ onSubmit: async name => {
+ await createGroup(name);
+ },
+ });
+ };
+
+ const onAddCategory = (groupId, isIncome) => {
+ pushModal('new-category', {
+ onValidate: name => (!name ? 'Name is required.' : null),
+ onSubmit: async name => {
+ collapseModals('category-group-menu');
+ await createCategory(name, groupId, isIncome, false);
+ },
+ });
+ };
+
+ const onSaveGroup = group => {
+ updateGroup(group);
+ };
+
+ const onDeleteGroup = async groupId => {
+ const group = categoryGroups?.find(g => g.id === groupId);
+
+ if (!group) {
+ return;
+ }
+
+ let mustTransfer = false;
+ for (const category of group.categories ?? []) {
+ if (await send('must-category-transfer', { id: category.id })) {
+ mustTransfer = true;
+ break;
+ }
+ }
+
+ if (mustTransfer) {
+ pushModal('confirm-category-delete', {
+ group: groupId,
+ onDelete: transferCategory => {
+ collapseModals('category-group-menu');
+ deleteGroup(groupId, transferCategory);
+ },
+ });
+ } else {
+ collapseModals('category-group-menu');
+ deleteGroup(groupId);
+ }
+ };
+
+ const onSaveCategory = category => {
+ updateCategory(category);
+ };
+
+ const onDeleteCategory = async categoryId => {
+ const mustTransfer = await send('must-category-transfer', {
+ id: categoryId,
+ });
+
+ if (mustTransfer) {
+ pushModal('confirm-category-delete', {
+ category: categoryId,
+ onDelete: transferCategory => {
+ if (categoryId !== transferCategory) {
+ collapseModals('category-menu');
+ deleteCategory(categoryId, transferCategory);
+ }
+ },
+ });
+ } else {
+ collapseModals('category-menu');
+ deleteCategory(categoryId);
+ }
+ };
+
+ const onReorderCategory = (id, { inGroup, aroundCategory }) => {
+ let groupId, targetId;
+
+ if (inGroup) {
+ groupId = inGroup;
+ } else if (aroundCategory) {
+ const { id: originalCatId, position } = aroundCategory;
+
+ let catId = originalCatId;
+ const group = categoryGroups.find(group =>
+ group.categories?.find(cat => cat.id === catId),
+ );
+
+ if (position === 'bottom') {
+ const idx = group?.categories?.findIndex(cat => cat.id === catId) ?? -1;
+ catId = group?.categories
+ ? idx < group.categories.length - 1
+ ? group.categories[idx + 1].id
+ : null
+ : null;
+ }
+
+ groupId = group?.id;
+ targetId = catId;
+ }
+
+ moveCategory(id, groupId, targetId);
+ };
+
+ const onReorderGroup = (id, targetId, position) => {
+ if (position === 'bottom') {
+ const idx = categoryGroups.findIndex(group => group.id === targetId);
+ targetId =
+ idx < categoryGroups.length - 1 ? categoryGroups[idx + 1].id : null;
+ }
+
+ moveCategoryGroup(id, targetId);
+ };
+
+ const sync = async () => {
+ const result = await props.sync();
+ if (result?.error) {
+ return 'error';
+ } else if (result) {
+ return 'updated';
+ }
+ return null;
+ };
+
+ const onPrevMonth = async () => {
+ const month = monthUtils.subMonths(currentMonth, 1);
+ await prewarmMonth(budgetType, spreadsheet, month);
+ setCurrentMonth(month);
+ setInitialized(true);
+ };
+
+ const onNextMonth = async () => {
+ const month = monthUtils.addMonths(currentMonth, 1);
+ await prewarmMonth(budgetType, spreadsheet, month);
+ setCurrentMonth(month);
+ setInitialized(true);
+ };
+
+ // const onOpenMonthActionMenu = () => {
+ // const options = [
+ // 'Copy last month’s budget',
+ // 'Set budgets to zero',
+ // 'Set budgets to 3 month average',
+ // budgetType === 'report' && 'Apply to all future budgets',
+ // ].filter(Boolean);
+
+ // props.showActionSheetWithOptions(
+ // {
+ // options,
+ // cancelButtonIndex: options.length - 1,
+ // title: 'Actions',
+ // },
+ // idx => {
+ // switch (idx) {
+ // case 0:
+ // setEditMode(true);
+ // break;
+ // case 1:
+ // onBudgetAction('copy-last');
+ // break;
+ // case 2:
+ // onBudgetAction('set-zero');
+ // break;
+ // case 3:
+ // onBudgetAction('set-3-avg');
+ // break;
+ // case 4:
+ // if (budgetType === 'report') {
+ // onBudgetAction('set-all-future');
+ // }
+ // break;
+ // default:
+ // }
+ // },
+ // );
+ // };
+
+ const onSwitchBudgetType = async () => {
+ setInitialized(false);
+
+ const newBudgetType = budgetType === 'rollover' ? 'report' : 'rollover';
+ await switchBudgetType(
+ newBudgetType,
+ spreadsheet,
+ bounds,
+ currentMonth,
+ () => loadPrefs(),
+ );
+
+ setInitialized(true);
+ };
+
+ const onSaveNotes = async (id, notes) => {
+ await send('notes-save', { id, note: notes });
+ };
+
+ const onEditGroupNotes = id => {
+ const group = categoryGroups.find(g => g.id === id);
+ pushModal('notes', {
+ id,
+ name: group.name,
+ onSave: onSaveNotes,
+ });
+ };
+
+ const onEditCategoryNotes = id => {
+ const category = categories.find(c => c.id === id);
+ pushModal('notes', {
+ id,
+ name: category.name,
+ onSave: onSaveNotes,
+ });
+ };
+
+ const onEditGroup = id => {
+ const group = categoryGroups.find(g => g.id === id);
+ pushModal('category-group-menu', {
+ groupId: group.id,
+ onSave: onSaveGroup,
+ onAddCategory,
+ onEditNotes: onEditGroupNotes,
+ onDelete: onDeleteGroup,
+ });
+ };
+
+ const onEditCategory = id => {
+ const category = categories.find(c => c.id === id);
+ pushModal('category-menu', {
+ categoryId: category.id,
+ onSave: onSaveCategory,
+ onEditNotes: onEditCategoryNotes,
+ onDelete: onDeleteCategory,
+ });
+ };
+
+ const onEditCategoryBudget = id => {
+ onEdit(CATEGORY_BUDGET_EDIT_ACTION, id);
+ };
+
+ const onOpenBalanceActionMenu = id => {
+ onEdit(BALANCE_MENU_OPEN_ACTION, id);
+ };
+
+ const onEdit = (action, id) => {
+ // Do not allow editing if another field is currently being edited.
+ // Cancel the currently editing field in that case.
+ const currentlyEditing = editingBudgetCategoryId || openBalanceActionMenuId;
+
+ setEditingBudgetCategoryId(
+ action === CATEGORY_BUDGET_EDIT_ACTION && !currentlyEditing ? id : null,
+ );
+ setOpenBalanceActionMenuId(
+ action === BALANCE_MENU_OPEN_ACTION && !currentlyEditing ? id : null,
+ );
+
+ return { action, editingId: !currentlyEditing ? id : null };
+ };
+
+ const numberFormat = prefs?.numberFormat || 'comma-dot';
+ const hideFraction = prefs?.hideFraction || false;
+
+ if (!categoryGroups || !initialized) {
+ return (
+ <View
+ style={{
+ flex: 1,
+ backgroundColor: theme.mobilePageBackground,
+ alignItems: 'center',
+ justifyContent: 'center',
+ marginBottom: 25,
+ }}
+ >
+ <AnimatedLoading width={25} height={25} />
+ </View>
+ );
+ }
+
+ return (
+ <SyncRefresh
+ onSync={async () => {
+ await sync();
+ }}
+ >
+ {({ refreshing, onRefresh }) => (
+ <BudgetTable
+ // This key forces the whole table rerender when the number
+ // format changes
+ key={numberFormat + hideFraction}
+ categoryGroups={categoryGroups}
+ categories={categories}
+ type={budgetType}
+ month={currentMonth}
+ monthBounds={bounds}
+ // refreshControl={
+ // <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
+ // }
+ editMode={editMode}
+ onEditMode={flag => setEditMode(flag)}
+ onShowBudgetSummary={onShowBudgetSummary}
+ onPrevMonth={onPrevMonth}
+ onNextMonth={onNextMonth}
+ onSaveGroup={onSaveGroup}
+ onDeleteGroup={onDeleteGroup}
+ onAddGroup={onAddGroup}
+ onAddCategory={onAddCategory}
+ onSaveCategory={onSaveCategory}
+ onDeleteCategory={onDeleteCategory}
+ onReorderCategory={onReorderCategory}
+ onReorderGroup={onReorderGroup}
+ onOpenMonthActionMenu={() => {}} //onOpenMonthActionMenu}
+ onBudgetAction={applyBudgetAction}
+ onRefresh={onRefresh}
+ onSwitchBudgetType={onSwitchBudgetType}
+ onSaveNotes={onSaveNotes}
+ onEditGroupNotes={onEditGroupNotes}
+ onEditCategoryNotes={onEditCategoryNotes}
+ savePrefs={savePrefs}
+ pushModal={pushModal}
+ onEditGroup={onEditGroup}
+ onEditCategory={onEditCategory}
+ editingBudgetCategoryId={editingBudgetCategoryId}
+ onEditCategoryBudget={onEditCategoryBudget}
+ openBalanceActionMenuId={openBalanceActionMenuId}
+ onOpenBalanceActionMenu={onOpenBalanceActionMenu}
+ />
+ )}
+ </SyncRefresh>
+ );
+}
+
+export function Budget() {
+ const { list: categories, grouped: categoryGroups } = useCategories();
+ const budgetType = useSelector(
+ state => state.prefs.local?.budgetType || 'rollover',
+ );
+ const prefs = useSelector(state => state.prefs.local);
+
+ const actions = useActions();
+ const spreadsheet = useSpreadsheet();
+ useSetThemeColor(theme.mobileViewTheme);
+ return (
+ <BudgetInner
+ categoryGroups={categoryGroups}
+ categories={categories}
+ budgetType={budgetType}
+ prefs={prefs}
+ {...actions}
+ spreadsheet={spreadsheet}
+ />
+ );
+}
diff --git a/packages/desktop-client/src/components/reports/ReportOptions.ts b/packages/desktop-client/src/components/reports/ReportOptions.ts
index 2642e63435..014d011c84 100644
--- a/packages/desktop-client/src/components/reports/ReportOptions.ts
+++ b/packages/desktop-client/src/components/reports/ReportOptions.ts
@@ -63,7 +63,10 @@ export type QueryDataEntity = {
amount: number;
};
-export type UncategorizedEntity = CategoryEntity & {
+export type UncategorizedEntity = Pick<
+ CategoryEntity,
+ 'name' | 'id' | 'hidden'
+> & {
/*
When looking at uncategorized and hidden transactions we
need a way to group them. To do this we give them a unique
@@ -71,10 +74,10 @@ export type UncategorizedEntity = CategoryEntity & {
transctions from our query. For this we use the 3 variables
below.
*/
- uncategorized_id: string;
- is_off_budget: boolean;
- is_transfer: boolean;
- has_category: boolean;
+ uncategorized_id?: string;
+ is_off_budget?: boolean;
+ is_transfer?: boolean;
+ has_category?: boolean;
};
const uncategorizedCategory: UncategorizedEntity = {
@@ -105,7 +108,10 @@ const offBudgetCategory: UncategorizedEntity = {
has_category: true,
};
-type UncategorizedGroupEntity = CategoryGroupEntity & {
+type UncategorizedGroupEntity = Pick<
+ CategoryGroupEntity,
+ 'name' | 'id' | 'hidden'
+> & {
categories?: UncategorizedEntity[];
};
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/grouped-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/grouped-spreadsheet.ts
index 46256aabba..968e6d5c33 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/grouped-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/grouped-spreadsheet.ts
@@ -85,7 +85,7 @@ export function createGroupedSpreadsheet({
let groupedAssets = 0;
let groupedDebts = 0;
- group.categories.map(item => {
+ group.categories.forEach(item => {
const monthAssets = filterHiddenItems(item, assets)
.filter(
asset => asset.date === month && asset.category === item.id,
@@ -99,8 +99,6 @@ export function createGroupedSpreadsheet({
)
.reduce((a, v) => (a = a + v.amount), 0);
groupedDebts += monthDebts;
-
- return null;
});
totalAssets += groupedAssets;
diff --git a/packages/loot-core/src/client/state-types/modals.d.ts b/packages/loot-core/src/client/state-types/modals.d.ts
index 36771e2e98..c1d3a9ee33 100644
--- a/packages/loot-core/src/client/state-types/modals.d.ts
+++ b/packages/loot-core/src/client/state-types/modals.d.ts
@@ -131,6 +131,23 @@ type FinanceModals = {
name: string;
onSave: (id: string, notes: string) => void;
};
+ 'report-budget-summary': { month: string };
+ 'rollover-budget-summary': {
+ month: string;
+ onBudgetAction: (
+ month: string,
+ type: string,
+ args: unknown,
+ ) => Promise<void>;
+ };
+ 'new-category-group': {
+ onValidate?: (value: string) => string;
+ onSubmit: (value: string) => Promise<void>;
+ };
+ 'new-category': {
+ onValidate?: (value: string) => string;
+ onSubmit: (value: string) => Promise<void>;
+ };
};
export type PushModalAction = {
diff --git a/packages/loot-core/src/types/models/category-group.d.ts b/packages/loot-core/src/types/models/category-group.d.ts
index 4225ad6838..19dfeab569 100644
--- a/packages/loot-core/src/types/models/category-group.d.ts
+++ b/packages/loot-core/src/types/models/category-group.d.ts
@@ -1,3 +1,5 @@
+import { CategoryEntity } from './category';
+
export interface CategoryGroupEntity {
id?: string;
name: string;
diff --git a/packages/loot-core/src/types/server-handlers.d.ts b/packages/loot-core/src/types/server-handlers.d.ts
index 1f0d276e49..5a6487b21a 100644
--- a/packages/loot-core/src/types/server-handlers.d.ts
+++ b/packages/loot-core/src/types/server-handlers.d.ts
@@ -5,13 +5,16 @@ import { Backup } from '../server/backups';
import { RemoteFile } from '../server/cloud-storage';
import { Node as SpreadsheetNode } from '../server/spreadsheet/spreadsheet';
import { Message } from '../server/sync';
+import { QueryState } from '../shared/query';
+import { Budget } from './budget';
import {
AccountEntity,
CategoryEntity,
CategoryGroupEntity,
GoCardlessToken,
GoCardlessInstitution,
+ PayeeEntity,
} from './models';
import { EmptyObject } from './util';
@@ -31,8 +34,6 @@ export interface ServerHandlers {
'transaction-add': (transaction) => Promise<EmptyObject>;
- 'transaction-add': (transaction) => Promise<EmptyObject>;
-
'transaction-delete': (transaction) => Promise<EmptyObject>;
'transactions-parse-file': (arg: {
@@ -47,7 +48,7 @@ export interface ServerHandlers {
payees;
}) => Promise<unknown>;
- 'transactions-export-query': (arg: { query: queryState }) => Promise<unknown>;
+ 'transactions-export-query': (arg: { query: QueryState }) => Promise<unknown>;
'get-categories': () => Promise<{
grouped: Array<CategoryGroupEntity>;
@@ -252,10 +253,7 @@ export interface ServerHandlers {
'make-plaid-public-token': (arg: {
bankId;
- }) => Promise<
- | { error: ''; code: data.error_code; type: data.error_type }
- | { linkToken: data.link_token }
- >;
+ }) => Promise<{ error: ''; code; type } | { linkToken }>;
'save-global-prefs': (prefs) => Promise<'ok'>;
@@ -280,9 +278,9 @@ export interface ServerHandlers {
'get-did-bootstrap': () => Promise<boolean>;
- 'subscribe-needs-bootstrap': (
- args: { url } = {},
- ) => Promise<
+ 'subscribe-needs-bootstrap': (args: {
+ url;
+ }) => Promise<
{ error: string } | { bootstrapped: unknown; hasServer: boolean }
>;
@@ -318,7 +316,7 @@ export interface ServerHandlers {
'reset-budget-cache': () => Promise<unknown>;
- 'upload-budget': (arg: { id } = {}) => Promise<{ error?: string }>;
+ 'upload-budget': (arg: { id }) => Promise<{ error?: string }>;
'download-budget': (arg: { fileId; replace? }) => Promise<{ error; id }>;
diff --git a/upcoming-release-notes/2081.md b/upcoming-release-notes/2081.md
new file mode 100644
index 0000000000..7f85c27593
--- /dev/null
+++ b/upcoming-release-notes/2081.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [joel-jeremy]
+---
+
+Refactored MobileBudget component to TypeScript