Skip to content

Commit

Permalink
Merge branch 'actualbudget:master' into sidebar
Browse files Browse the repository at this point in the history
  • Loading branch information
tlesicka authored Sep 17, 2024
2 parents 7ab35b9 + 17fd068 commit 3d755bb
Show file tree
Hide file tree
Showing 19 changed files with 65 additions and 101 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
} from 'loot-core/src/types/models';

import { useCategories } from '../../hooks/useCategories';
import { useMetadataPref } from '../../hooks/useMetadataPref';
import { useSyncedPref } from '../../hooks/useSyncedPref';
import { SvgSplit } from '../../icons/v0';
import { useResponsive } from '../../ResponsiveProvider';
import { type CSSProperties, theme, styles } from '../../style';
Expand Down Expand Up @@ -379,7 +379,7 @@ function CategoryItem({
borderTop: `1px solid ${theme.pillBorder}`,
}
: {};
const [budgetType = 'rollover'] = useMetadataPref('budgetType');
const [budgetType = 'rollover'] = useSyncedPref('budgetType');

const balanceBinding =
budgetType === 'rollover'
Expand Down
4 changes: 2 additions & 2 deletions packages/desktop-client/src/components/budget/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ import * as monthUtils from 'loot-core/src/shared/months';
import { useCategories } from '../../hooks/useCategories';
import { useGlobalPref } from '../../hooks/useGlobalPref';
import { useLocalPref } from '../../hooks/useLocalPref';
import { useMetadataPref } from '../../hooks/useMetadataPref';
import { useNavigate } from '../../hooks/useNavigate';
import { useSyncedPref } from '../../hooks/useSyncedPref';
import { styles } from '../../style';
import { View } from '../common/View';
import { NamespaceContext } from '../spreadsheet/NamespaceContext';
Expand Down Expand Up @@ -78,7 +78,7 @@ function BudgetInner(props: BudgetInnerProps) {
start: startMonth,
end: startMonth,
});
const [budgetType = 'rollover'] = useMetadataPref('budgetType');
const [budgetType = 'rollover'] = useSyncedPref('budgetType');
const [maxMonthsPref] = useGlobalPref('maxMonths');
const maxMonths = maxMonthsPref || 1;
const [initialized, setInitialized] = useState(false);
Expand Down
20 changes: 3 additions & 17 deletions packages/desktop-client/src/components/budget/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { send } from 'loot-core/src/platform/client/fetch';
import * as monthUtils from 'loot-core/src/shared/months';
import { type Handlers } from 'loot-core/src/types/handlers';
import { type CategoryGroupEntity } from 'loot-core/src/types/models';
import { type MetadataPrefs } from 'loot-core/src/types/prefs';
import { type SyncedPrefs } from 'loot-core/src/types/prefs';

import { type CSSProperties, styles, theme } from '../../style';
import { type DropPosition } from '../sort';
Expand Down Expand Up @@ -141,7 +141,7 @@ export function getScrollbarWidth() {
}

export async function prewarmMonth(
budgetType: MetadataPrefs['budgetType'],
budgetType: SyncedPrefs['budgetType'],
spreadsheet: ReturnType<typeof useSpreadsheet>,
month: string,
) {
Expand All @@ -156,7 +156,7 @@ export async function prewarmMonth(
}

export async function prewarmAllMonths(
budgetType: MetadataPrefs['budgetType'],
budgetType: SyncedPrefs['budgetType'],
spreadsheet: ReturnType<typeof useSpreadsheet>,
bounds: { start: string; end: string },
startMonth: string,
Expand All @@ -174,17 +174,3 @@ export async function prewarmAllMonths(
months.map(month => prewarmMonth(budgetType, spreadsheet, month)),
);
}

export async function switchBudgetType(
newBudgetType: MetadataPrefs['budgetType'],
spreadsheet: ReturnType<typeof useSpreadsheet>,
bounds: { start: string; end: string },
startMonth: string,
onSuccess: () => Promise<void> | undefined,
) {
spreadsheet.disableObservers();
await send('budget-set-type', { type: newBudgetType });
await prewarmAllMonths(newBudgetType, spreadsheet, bounds, startMonth);
spreadsheet.enableObservers();
await onSuccess?.();
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import * as monthUtils from 'loot-core/src/shared/months';
import { useCategories } from '../../../hooks/useCategories';
import { useFeatureFlag } from '../../../hooks/useFeatureFlag';
import { useLocalPref } from '../../../hooks/useLocalPref';
import { useMetadataPref } from '../../../hooks/useMetadataPref';
import { useNavigate } from '../../../hooks/useNavigate';
import { useNotes } from '../../../hooks/useNotes';
import { useSyncedPref } from '../../../hooks/useSyncedPref';
import { useUndo } from '../../../hooks/useUndo';
import { SvgLogo } from '../../../icons/logo';
import { SvgExpandArrow } from '../../../icons/v0';
Expand Down Expand Up @@ -225,7 +225,7 @@ function BudgetCell({
}) {
const dispatch = useDispatch();
const { showUndoNotification } = useUndo();
const [budgetType = 'rollover'] = useMetadataPref('budgetType');
const [budgetType = 'rollover'] = useSyncedPref('budgetType');

const categoryBudgetMenuModal = `${budgetType}-budget-menu`;
const categoryNotes = useNotes(category.id);
Expand Down Expand Up @@ -358,7 +358,7 @@ const ExpenseCategory = memo(function ExpenseCategory({
const goalTemp = useSheetValue(goal);
const goalValue = isGoalTemplatesEnabled ? goalTemp : null;

const [budgetType = 'rollover'] = useMetadataPref('budgetType');
const [budgetType = 'rollover'] = useSyncedPref('budgetType');
const dispatch = useDispatch();
const { showUndoNotification } = useUndo();
const { list: categories } = useCategories();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import * as monthUtils from 'loot-core/src/shared/months';

import { useCategories } from '../../../hooks/useCategories';
import { useLocalPref } from '../../../hooks/useLocalPref';
import { useMetadataPref } from '../../../hooks/useMetadataPref';
import { useSetThemeColor } from '../../../hooks/useSetThemeColor';
import { useSyncedPref } from '../../../hooks/useSyncedPref';
import { AnimatedLoading } from '../../../icons/AnimatedLoading';
Expand All @@ -43,7 +42,7 @@ export function Budget() {
useSetThemeColor(theme.mobileViewTheme);

const { list: categories, grouped: categoryGroups } = useCategories();
const [budgetTypePref] = useMetadataPref('budgetType');
const [budgetTypePref] = useSyncedPref('budgetType');
const budgetType = isBudgetType(budgetTypePref) ? budgetTypePref : 'rollover';
const spreadsheet = useSpreadsheet();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,58 +1,27 @@
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import React from 'react';

import { loadPrefs } from 'loot-core/src/client/actions';
import { useSpreadsheet } from 'loot-core/src/client/SpreadsheetProvider';
import * as monthUtils from 'loot-core/src/shared/months';

import { useLocalPref } from '../../hooks/useLocalPref';
import { useMetadataPref } from '../../hooks/useMetadataPref';
import { switchBudgetType } from '../budget/util';
import { ButtonWithLoading } from '../common/Button2';
import { useSyncedPref } from '../../hooks/useSyncedPref';
import { Button } from '../common/Button2';
import { Link } from '../common/Link';
import { Text } from '../common/Text';

import { Setting } from './UI';

export function BudgetTypeSettings() {
const dispatch = useDispatch();
const [budgetType = 'rollover'] = useMetadataPref('budgetType');
const [loading, setLoading] = useState(false);

const currentMonth = monthUtils.currentMonth();
const [startMonthPref] = useLocalPref('budget.startMonth');
const startMonth = startMonthPref || currentMonth;
const spreadsheet = useSpreadsheet();
const [budgetType = 'rollover', setBudgetType] = useSyncedPref('budgetType');

function onSwitchType() {
setLoading(true);

if (!loading) {
const newBudgetType = budgetType === 'rollover' ? 'report' : 'rollover';

switchBudgetType(
newBudgetType,
spreadsheet,
{
start: startMonth,
end: startMonth,
},
startMonth,
async () => {
dispatch(loadPrefs());
setLoading(false);
},
);
}
const newBudgetType = budgetType === 'rollover' ? 'report' : 'rollover';
setBudgetType(newBudgetType);
}

return (
<Setting
primaryAction={
<ButtonWithLoading isLoading={loading} onPress={onSwitchType}>
<Button onPress={onSwitchType}>
Switch to {budgetType === 'report' ? 'envelope' : 'tracking'}{' '}
budgeting
</ButtonWithLoading>
</Button>
}
>
<Text>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Trans, useTranslation } from 'react-i18next';
import type { FeatureFlag } from 'loot-core/src/types/prefs';

import { useFeatureFlag } from '../../hooks/useFeatureFlag';
import { useMetadataPref } from '../../hooks/useMetadataPref';
import { useSyncedPref } from '../../hooks/useSyncedPref';
import { theme } from '../../style';
import { Link } from '../common/Link';
Expand Down Expand Up @@ -70,7 +69,7 @@ function FeatureToggle({

function ReportBudgetFeature() {
const { t } = useTranslation();
const [budgetType = 'rollover'] = useMetadataPref('budgetType');
const [budgetType = 'rollover'] = useSyncedPref('budgetType');
const enabled = useFeatureFlag('reportBudget');
const blockToggleOff = budgetType === 'report' && enabled;
return (
Expand Down
2 changes: 1 addition & 1 deletion packages/loot-core/migrations/1723665565000_prefs.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const SYNCED_PREF_KEYS = [
/^csv-has-header-/,
/^ofx-fallback-missing-payee-/,
/^flip-amount-/,
// 'budgetType', // TODO: uncomment when `budgetType` moves from metadata to synced prefs
'budgetType',
/^flags\./,
];

Expand Down
11 changes: 10 additions & 1 deletion packages/loot-core/src/server/accounts/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ function getAccountBalance(account) {
}
}

async function updateAccountBalance(id, balance) {
await db.runQuery('UPDATE accounts SET balance_current = ? WHERE id = ?', [
amountToInteger(balance),
id,
]);
}

export async function getGoCardlessAccounts(userId, userKey, id) {
const userToken = await asyncStorage.getItem('user-token');
if (!userToken) return;
Expand Down Expand Up @@ -694,7 +701,7 @@ export async function syncAccount(
);
}

const { transactions: originalTransactions } = download;
const { transactions: originalTransactions, accountBalance } = download;

if (originalTransactions.length === 0) {
return { added: [], updated: [] };
Expand All @@ -713,6 +720,8 @@ export async function syncAccount(
useStrictIdChecking,
);

if (accountBalance) await updateAccountBalance(id, accountBalance);

return result;
});
} else {
Expand Down
9 changes: 5 additions & 4 deletions packages/loot-core/src/server/budget/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import * as monthUtils from '../../shared/months';
import { safeNumber } from '../../shared/util';
import * as db from '../db';
import * as prefs from '../prefs';
import * as sheet from '../sheet';
import { batchMessages } from '../sync';

Expand All @@ -28,12 +27,14 @@ function calcBufferedAmount(
}

function getBudgetTable(): string {
const { budgetType } = prefs.getPrefs() || {};
return budgetType === 'report' ? 'reflect_budgets' : 'zero_budgets';
return isReflectBudget() ? 'reflect_budgets' : 'zero_budgets';
}

export function isReflectBudget(): boolean {
const { budgetType } = prefs.getPrefs();
const budgetType =
db.firstSync(`SELECT value FROM preferences WHERE id = ?`, [
'budgetType',
]) ?? 'rollover';
return budgetType === 'report';
}

Expand Down
20 changes: 5 additions & 15 deletions packages/loot-core/src/server/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,20 +268,6 @@ handlers['report-budget-month'] = async function ({ month }) {
return values;
};

handlers['budget-set-type'] = async function ({ type }) {
if (!prefs.BUDGET_TYPES.includes(type)) {
throw new Error('Invalid budget type: ' + type);
}

// It's already the same; don't do anything
if (type === prefs.getPrefs().budgetType) {
return;
}

// Save prefs
return prefs.savePrefs({ budgetType: type });
};

handlers['category-create'] = mutator(async function ({
name,
groupId,
Expand Down Expand Up @@ -1991,7 +1977,11 @@ async function loadBudget(id) {
}

// This is a bit leaky, but we need to set the initial budget type
sheet.get().meta().budgetType = prefs.getPrefs().budgetType;
const { value: budgetType = 'rollover' } =
(await db.first('SELECT value from preferences WHERE id = ?', [
'budgetType',
])) ?? {};
sheet.get().meta().budgetType = budgetType;
await budget.createAllBudgets();

// Load all the in-memory state
Expand Down
2 changes: 1 addition & 1 deletion packages/loot-core/src/server/prefs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export async function savePrefs(
// Sync whitelisted prefs
const messages: Message[] = Object.keys(prefsToSet)
.map(key => {
if (key === 'budgetType' || key === 'budgetName') {
if (key === 'budgetName') {
return {
dataset: 'prefs',
row: key,
Expand Down
6 changes: 4 additions & 2 deletions packages/loot-core/src/server/sheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import * as sqlite from '../platform/server/sqlite';
import { sheetForMonth } from '../shared/months';

import * as Platform from './platform';
import * as prefs from './prefs';
import { Spreadsheet } from './spreadsheet/spreadsheet';
import { resolveName } from './spreadsheet/util';

Expand Down Expand Up @@ -196,7 +195,10 @@ export async function loadUserBudgets(db): Promise<void> {
// TODO: Clear out the cache here so make sure future loads of the app
// don't load any extra values that aren't set here

const { budgetType } = prefs.getPrefs() || {};
const { value: budgetType = 'rollover' } =
(await db.first('SELECT value from preferences WHERE id = ?', [
'budgetType',
])) ?? {};

const table = budgetType === 'report' ? 'reflect_budgets' : 'zero_budgets';
const budgets = await db.all(`
Expand Down
10 changes: 5 additions & 5 deletions packages/loot-core/src/server/sync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,11 @@ export const applyMessages = sequential(async (messages: Message[]) => {

currentMerkle = merkle.insert(currentMerkle, timestamp);
}

// Special treatment for some synced prefs
if (dataset === 'preferences' && row === 'budgetType') {
setBudgetType(value);
}
}

if (checkSyncingMode('enabled')) {
Expand All @@ -384,11 +389,6 @@ export const applyMessages = sequential(async (messages: Message[]) => {
// Save any synced prefs
if (Object.keys(prefsToSet).length > 0) {
prefs.savePrefs(prefsToSet, { avoidSync: true });

if (prefsToSet.budgetType) {
setBudgetType(prefsToSet.budgetType);
}

connection.send('prefs-updated');
}

Expand Down
3 changes: 1 addition & 2 deletions packages/loot-core/src/types/prefs.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type FeatureFlag =
*/
export type SyncedPrefs = Partial<
Record<
| 'budgetType'
| 'firstDayOfWeekIdx'
| 'dateFormat'
| 'numberFormat'
Expand Down Expand Up @@ -39,8 +40,6 @@ export type SyncedPrefs = Partial<
* core database.
*/
export type MetadataPrefs = Partial<{
// TODO: move budgetType to SyncedPrefs
budgetType: string;
budgetName: string;
id: string;
lastUploaded: string;
Expand Down
2 changes: 0 additions & 2 deletions packages/loot-core/src/types/server-handlers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,6 @@ export interface ServerHandlers {
}[]
>;

'budget-set-type': (arg: { type }) => Promise<unknown>;

'category-create': (arg: {
name;
groupId;
Expand Down
2 changes: 1 addition & 1 deletion upcoming-release-notes/3352.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ category: Maintenance
authors: [nmathey]
---

Support translations in Translation support for desktop-client/src/components/budget/BalanceWithCarryover.tsx
Support translations in Translation support for desktop-client/src/components/budget/BalanceWithCarryover.tsx
Loading

0 comments on commit 3d755bb

Please sign in to comment.