Skip to content

A local-first personal finance app

[Final PR] Move remaining loot-core/client files to desktop-client feature folders (#4830)

Joel Jeremy Marquez720d0fda6dc1
diff --git a/packages/desktop-client/src/browser-preload.browser.js b/packages/desktop-client/src/browser-preload.browser.js
index 5dc18eda89..f1409f4828 100644
--- a/packages/desktop-client/src/browser-preload.browser.js
+++ b/packages/desktop-client/src/browser-preload.browser.js
@@ -2,7 +2,7 @@ import { initBackend as initSQLBackend } from 'absurd-sql/dist/indexeddb-main-th
// eslint-disable-next-line import/no-unresolved
import { registerSW } from 'virtual:pwa-register';
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
import packageJson from '../package.json';
diff --git a/packages/desktop-client/src/components/App.tsx b/packages/desktop-client/src/components/App.tsx
index 2ff688d090..f7c7534072 100644
--- a/packages/desktop-client/src/components/App.tsx
+++ b/packages/desktop-client/src/components/App.tsx
@@ -14,9 +14,8 @@ import { BrowserRouter } from 'react-router-dom';
import { styles } from '@actual-app/components/styles';
import { View } from '@actual-app/components/view';
-import * as Platform from 'loot-core/client/platform';
-import { SpreadsheetProvider } from 'loot-core/client/SpreadsheetProvider';
import { init as initConnection, send } from 'loot-core/platform/client/fetch';
+import * as Platform from 'loot-core/shared/platform';
import { setAppState, sync } from '../app/appSlice';
import { closeBudget, loadBudget } from '../budgets/budgetsSlice';
@@ -41,6 +40,7 @@ import { SidebarProvider } from './sidebar/SidebarProvider';
import { UpdateNotification } from './UpdateNotification';
import { useMetadataPref } from '@desktop-client/hooks/useMetadataPref';
+import { SpreadsheetProvider } from '@desktop-client/hooks/useSpreadsheet';
function AppInner() {
const [budgetId] = useMetadataPref('id');
diff --git a/packages/desktop-client/src/components/GlobalKeys.ts b/packages/desktop-client/src/components/GlobalKeys.ts
index 615c6085b4..0c76a883eb 100644
--- a/packages/desktop-client/src/components/GlobalKeys.ts
+++ b/packages/desktop-client/src/components/GlobalKeys.ts
@@ -1,6 +1,6 @@
import { useEffect } from 'react';
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
import { useNavigate } from '@desktop-client/hooks/useNavigate';
diff --git a/packages/desktop-client/src/components/Titlebar.tsx b/packages/desktop-client/src/components/Titlebar.tsx
index 2460d53355..b177a8abf5 100644
--- a/packages/desktop-client/src/components/Titlebar.tsx
+++ b/packages/desktop-client/src/components/Titlebar.tsx
@@ -19,15 +19,15 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import * as Platform from 'loot-core/client/platform';
-import * as queries from 'loot-core/client/queries';
import { listen } from 'loot-core/platform/client/fetch';
import {
isDevelopmentEnvironment,
isElectron,
} from 'loot-core/shared/environment';
+import * as Platform from 'loot-core/shared/platform';
import { sync } from '../app/appSlice';
+import * as queries from '../queries/queries';
import { useDispatch } from '../redux';
import { AccountSyncCheck } from './accounts/AccountSyncCheck';
diff --git a/packages/desktop-client/src/components/accounts/Account.tsx b/packages/desktop-client/src/components/accounts/Account.tsx
index e20f6d9808..34f0321310 100644
--- a/packages/desktop-client/src/components/accounts/Account.tsx
+++ b/packages/desktop-client/src/components/accounts/Account.tsx
@@ -16,12 +16,6 @@ import { debounce } from 'debounce';
import { t } from 'i18next';
import { v4 as uuidv4 } from 'uuid';
-import * as queries from 'loot-core/client/queries';
-import {
- aqlQuery,
- pagedQuery,
- type PagedQuery,
-} from 'loot-core/client/query-helpers';
import { send, listen } from 'loot-core/platform/client/fetch';
import * as undo from 'loot-core/platform/client/undo';
import { type UndoState } from 'loot-core/server/undo';
@@ -53,6 +47,9 @@ import {
replaceModal,
} from '../../modals/modalsSlice';
import { addNotification } from '../../notifications/notificationsSlice';
+import { aqlQuery } from '../../queries/aqlQuery';
+import { pagedQuery, type PagedQuery } from '../../queries/pagedQuery';
+import * as queries from '../../queries/queries';
import {
createPayee,
initiallyLoadPayees,
diff --git a/packages/desktop-client/src/components/accounts/Reconcile.tsx b/packages/desktop-client/src/components/accounts/Reconcile.tsx
index 5aa450d90c..d20e0c7842 100644
--- a/packages/desktop-client/src/components/accounts/Reconcile.tsx
+++ b/packages/desktop-client/src/components/accounts/Reconcile.tsx
@@ -11,16 +11,17 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { t } from 'i18next';
-import * as queries from 'loot-core/client/queries';
import { type Query } from 'loot-core/shared/query';
import { currencyToInteger, tsToRelativeTime } from 'loot-core/shared/util';
import { type AccountEntity } from 'loot-core/types/models';
import { type TransObjectLiteral } from 'loot-core/types/util';
-import { useLocale } from '../../hooks/useLocale';
+import * as queries from '../../queries/queries';
import { useFormat } from '../spreadsheet/useFormat';
import { useSheetValue } from '../spreadsheet/useSheetValue';
+import { useLocale } from '@desktop-client/hooks/useLocale';
+
type ReconcilingMessageProps = {
balanceQuery: { name: `balance-query-${string}`; query: Query };
targetBalance: number;
diff --git a/packages/desktop-client/src/components/autocomplete/CategoryAutocomplete.tsx b/packages/desktop-client/src/components/autocomplete/CategoryAutocomplete.tsx
index f2fc6083b2..08987de017 100644
--- a/packages/desktop-client/src/components/autocomplete/CategoryAutocomplete.tsx
+++ b/packages/desktop-client/src/components/autocomplete/CategoryAutocomplete.tsx
@@ -21,7 +21,6 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { css, cx } from '@emotion/css';
-import { trackingBudget, envelopeBudget } from 'loot-core/client/queries';
import { getNormalisedString } from 'loot-core/shared/normalisation';
import { integerToCurrency } from 'loot-core/shared/util';
import {
@@ -29,6 +28,7 @@ import {
type CategoryGroupEntity,
} from 'loot-core/types/models';
+import { trackingBudget, envelopeBudget } from '../../queries/queries';
import { useEnvelopeSheetValue } from '../budget/envelope/EnvelopeBudgetComponents';
import { makeAmountFullStyle } from '../budget/util';
import { useSheetValue } from '../spreadsheet/useSheetValue';
diff --git a/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx b/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx
index a51c9a804d..4edbdbdb47 100644
--- a/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx
+++ b/packages/desktop-client/src/components/budget/envelope/BalanceMenu.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { Menu } from '@actual-app/components/menu';
-import { envelopeBudget } from 'loot-core/client/queries';
+import { envelopeBudget } from '../../../queries/queries';
import { useEnvelopeSheetValue } from './EnvelopeBudgetComponents';
diff --git a/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.tsx b/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.tsx
index 045a1f9188..3931a8d003 100644
--- a/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.tsx
+++ b/packages/desktop-client/src/components/budget/envelope/BalanceMovementMenu.tsx
@@ -1,6 +1,6 @@
import React, { useCallback, useRef, useState } from 'react';
-import { envelopeBudget } from 'loot-core/client/queries';
+import { envelopeBudget } from '../../../queries/queries';
import { BalanceMenu } from './BalanceMenu';
import { CoverMenu } from './CoverMenu';
diff --git a/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx b/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx
index 0997f40704..6b3ac772b1 100644
--- a/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx
+++ b/packages/desktop-client/src/components/budget/envelope/EnvelopeBudgetComponents.tsx
@@ -19,7 +19,6 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import { envelopeBudget } from 'loot-core/client/queries';
import { evalArithmetic } from 'loot-core/shared/arithmetic';
import * as monthUtils from 'loot-core/shared/months';
import { integerToCurrency, amountToInteger } from 'loot-core/shared/util';
@@ -28,6 +27,7 @@ import {
type CategoryEntity,
} from 'loot-core/types/models';
+import { envelopeBudget } from '../../../queries/queries';
import { type Binding, type SheetFields } from '../../spreadsheet';
import { CellValue, CellValueText } from '../../spreadsheet/CellValue';
import { useSheetName } from '../../spreadsheet/useSheetName';
diff --git a/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudget.tsx b/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudget.tsx
index 15ebb4eb86..829fab8bcb 100644
--- a/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudget.tsx
+++ b/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudget.tsx
@@ -8,8 +8,7 @@ import React, {
import { Popover } from '@actual-app/components/popover';
import { View } from '@actual-app/components/view';
-import { envelopeBudget } from 'loot-core/client/queries';
-
+import { envelopeBudget } from '../../../../queries/queries';
import { CoverMenu } from '../CoverMenu';
import { useEnvelopeSheetValue } from '../EnvelopeBudgetComponents';
import { HoldMenu } from '../HoldMenu';
diff --git a/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudgetAmount.tsx b/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudgetAmount.tsx
index 716482db0d..c3eca7b73d 100644
--- a/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudgetAmount.tsx
+++ b/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudgetAmount.tsx
@@ -8,8 +8,7 @@ import { Tooltip } from '@actual-app/components/tooltip';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import { envelopeBudget } from 'loot-core/client/queries';
-
+import { envelopeBudget } from '../../../../queries/queries';
import { PrivacyFilter } from '../../../PrivacyFilter';
import { useFormat } from '../../../spreadsheet/useFormat';
import {
diff --git a/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudgetMenu.tsx b/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudgetMenu.tsx
index 3cb15da8dd..fcd8f5c2e0 100644
--- a/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudgetMenu.tsx
+++ b/packages/desktop-client/src/components/budget/envelope/budgetsummary/ToBudgetMenu.tsx
@@ -3,8 +3,7 @@ import { useTranslation } from 'react-i18next';
import { Menu } from '@actual-app/components/menu';
-import { envelopeBudget } from 'loot-core/client/queries';
-
+import { envelopeBudget } from '../../../../queries/queries';
import { useEnvelopeSheetValue } from '../EnvelopeBudgetComponents';
type ToBudgetMenuProps = Omit<
diff --git a/packages/desktop-client/src/components/budget/envelope/budgetsummary/TotalsList.tsx b/packages/desktop-client/src/components/budget/envelope/budgetsummary/TotalsList.tsx
index 07957345c6..39b783bafe 100644
--- a/packages/desktop-client/src/components/budget/envelope/budgetsummary/TotalsList.tsx
+++ b/packages/desktop-client/src/components/budget/envelope/budgetsummary/TotalsList.tsx
@@ -7,8 +7,7 @@ import { styles } from '@actual-app/components/styles';
import { Tooltip } from '@actual-app/components/tooltip';
import { View } from '@actual-app/components/view';
-import { envelopeBudget } from 'loot-core/client/queries';
-
+import { envelopeBudget } from '../../../../queries/queries';
import { CellValueText } from '../../../spreadsheet/CellValue';
import { useFormat } from '../../../spreadsheet/useFormat';
import { EnvelopeCellValue } from '../EnvelopeBudgetComponents';
diff --git a/packages/desktop-client/src/components/budget/index.tsx b/packages/desktop-client/src/components/budget/index.tsx
index 91563bacc0..bc404db3e0 100644
--- a/packages/desktop-client/src/components/budget/index.tsx
+++ b/packages/desktop-client/src/components/budget/index.tsx
@@ -5,7 +5,6 @@ import { useTranslation } from 'react-i18next';
import { styles } from '@actual-app/components/styles';
import { View } from '@actual-app/components/view';
-import { useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
@@ -37,6 +36,7 @@ import { useCategories } from '@desktop-client/hooks/useCategories';
import { useGlobalPref } from '@desktop-client/hooks/useGlobalPref';
import { useLocalPref } from '@desktop-client/hooks/useLocalPref';
import { useNavigate } from '@desktop-client/hooks/useNavigate';
+import { useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
type TrackingReportComponents = {
diff --git a/packages/desktop-client/src/components/budget/tracking/BalanceMenu.tsx b/packages/desktop-client/src/components/budget/tracking/BalanceMenu.tsx
index d5e39f3fce..a79a904e14 100644
--- a/packages/desktop-client/src/components/budget/tracking/BalanceMenu.tsx
+++ b/packages/desktop-client/src/components/budget/tracking/BalanceMenu.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { Menu } from '@actual-app/components/menu';
-import { trackingBudget } from 'loot-core/client/queries';
+import { trackingBudget } from '../../../queries/queries';
import { useTrackingSheetValue } from './TrackingBudgetComponents';
diff --git a/packages/desktop-client/src/components/budget/tracking/TrackingBudgetComponents.tsx b/packages/desktop-client/src/components/budget/tracking/TrackingBudgetComponents.tsx
index cba45be67c..295ffbd8fc 100644
--- a/packages/desktop-client/src/components/budget/tracking/TrackingBudgetComponents.tsx
+++ b/packages/desktop-client/src/components/budget/tracking/TrackingBudgetComponents.tsx
@@ -21,7 +21,6 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import { trackingBudget } from 'loot-core/client/queries';
import { evalArithmetic } from 'loot-core/shared/arithmetic';
import * as monthUtils from 'loot-core/shared/months';
import { integerToCurrency, amountToInteger } from 'loot-core/shared/util';
@@ -30,6 +29,7 @@ import {
type CategoryGroupEntity,
} from 'loot-core/types/models';
+import { trackingBudget } from '../../../queries/queries';
import { type Binding, type SheetFields } from '../../spreadsheet';
import { CellValue, CellValueText } from '../../spreadsheet/CellValue';
import { useSheetValue } from '../../spreadsheet/useSheetValue';
diff --git a/packages/desktop-client/src/components/budget/tracking/budgetsummary/ExpenseTotal.tsx b/packages/desktop-client/src/components/budget/tracking/budgetsummary/ExpenseTotal.tsx
index fa6c0e60d6..aaa2797612 100644
--- a/packages/desktop-client/src/components/budget/tracking/budgetsummary/ExpenseTotal.tsx
+++ b/packages/desktop-client/src/components/budget/tracking/budgetsummary/ExpenseTotal.tsx
@@ -1,7 +1,7 @@
import React, { type CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
-import { trackingBudget } from 'loot-core/client/queries';
+import { trackingBudget } from '../../../../queries/queries';
import { BudgetTotal } from './BudgetTotal';
import { ExpenseProgress } from './ExpenseProgress';
diff --git a/packages/desktop-client/src/components/budget/tracking/budgetsummary/IncomeTotal.tsx b/packages/desktop-client/src/components/budget/tracking/budgetsummary/IncomeTotal.tsx
index 11ad0be431..7806a4af78 100644
--- a/packages/desktop-client/src/components/budget/tracking/budgetsummary/IncomeTotal.tsx
+++ b/packages/desktop-client/src/components/budget/tracking/budgetsummary/IncomeTotal.tsx
@@ -1,7 +1,7 @@
import React, { type CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
-import { trackingBudget } from 'loot-core/client/queries';
+import { trackingBudget } from '../../../../queries/queries';
import { BudgetTotal } from './BudgetTotal';
import { IncomeProgress } from './IncomeProgress';
diff --git a/packages/desktop-client/src/components/budget/tracking/budgetsummary/Saved.tsx b/packages/desktop-client/src/components/budget/tracking/budgetsummary/Saved.tsx
index 07869d7181..40b2312339 100644
--- a/packages/desktop-client/src/components/budget/tracking/budgetsummary/Saved.tsx
+++ b/packages/desktop-client/src/components/budget/tracking/budgetsummary/Saved.tsx
@@ -9,8 +9,7 @@ import { Tooltip } from '@actual-app/components/tooltip';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import { trackingBudget } from 'loot-core/client/queries';
-
+import { trackingBudget } from '../../../../queries/queries';
import { PrivacyFilter } from '../../../PrivacyFilter';
import { useFormat } from '../../../spreadsheet/useFormat';
import { makeAmountFullStyle } from '../../util';
diff --git a/packages/desktop-client/src/components/budget/util.ts b/packages/desktop-client/src/components/budget/util.ts
index e68b214688..aff3380bc7 100644
--- a/packages/desktop-client/src/components/budget/util.ts
+++ b/packages/desktop-client/src/components/budget/util.ts
@@ -5,7 +5,6 @@ import { styles } from '@actual-app/components/styles';
import { theme } from '@actual-app/components/theme';
import { t } from 'i18next';
-import { type useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { type Handlers } from 'loot-core/types/handlers';
@@ -15,6 +14,7 @@ import {
} from 'loot-core/types/models';
import { type SyncedPrefs } from 'loot-core/types/prefs';
+import { type useSpreadsheet } from '../../hooks/useSpreadsheet';
import { type DropPosition } from '../sort';
import { getValidMonthBounds } from './MonthsContext';
diff --git a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
index 1ceddfb0df..dca0194fc9 100644
--- a/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/accounts/AccountTransactions.tsx
@@ -13,7 +13,6 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import * as queries from 'loot-core/client/queries';
import { listen, send } from 'loot-core/platform/client/fetch';
import { type Query } from 'loot-core/shared/query';
import { isPreviewId } from 'loot-core/shared/transactions';
@@ -28,6 +27,7 @@ import {
openAccountCloseModal,
pushModal,
} from '../../../modals/modalsSlice';
+import * as queries from '../../../queries/queries';
import {
markAccountRead,
reopenAccount,
diff --git a/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx b/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
index 19312ee093..7033f776bc 100644
--- a/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
+++ b/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
@@ -27,12 +27,12 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
-import * as queries from 'loot-core/client/queries';
import { type AccountEntity } from 'loot-core/types/models';
import { moveAccount } from '../../../accounts/accountsSlice';
import { syncAndDownload } from '../../../app/appSlice';
import { replaceModal } from '../../../modals/modalsSlice';
+import * as queries from '../../../queries/queries';
import { useDispatch, useSelector } from '../../../redux';
import { makeAmountFullStyle } from '../../budget/util';
import { MobilePageHeader, Page } from '../../Page';
diff --git a/packages/desktop-client/src/components/mobile/budget/BalanceCell.tsx b/packages/desktop-client/src/components/mobile/budget/BalanceCell.tsx
index 1276729e85..99c40c07f9 100644
--- a/packages/desktop-client/src/components/mobile/budget/BalanceCell.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/BalanceCell.tsx
@@ -9,7 +9,6 @@ import { View } from '@actual-app/components/view';
import { css, cx } from '@emotion/css';
import { AutoTextSize } from 'auto-text-size';
-import { envelopeBudget, trackingBudget } from 'loot-core/client/queries';
import { type CategoryEntity } from 'loot-core/types/models';
import { getColumnWidth, PILL_STYLE } from './BudgetTable';
@@ -19,6 +18,10 @@ import { PrivacyFilter } from '@desktop-client/components/PrivacyFilter';
import { type Binding } from '@desktop-client/components/spreadsheet';
import { useFormat } from '@desktop-client/components/spreadsheet/useFormat';
import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
+import {
+ envelopeBudget,
+ trackingBudget,
+} from '@desktop-client/queries/queries';
type BalanceCellProps = {
binding: Binding<
diff --git a/packages/desktop-client/src/components/mobile/budget/BudgetTable.jsx b/packages/desktop-client/src/components/mobile/budget/BudgetTable.jsx
index 32ef05b89e..209a82dde9 100644
--- a/packages/desktop-client/src/components/mobile/budget/BudgetTable.jsx
+++ b/packages/desktop-client/src/components/mobile/budget/BudgetTable.jsx
@@ -23,16 +23,16 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { AutoTextSize } from 'auto-text-size';
-import {
- envelopeBudget,
- trackingBudget,
- uncategorizedCount,
-} from 'loot-core/client/queries';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
import { groupById } from 'loot-core/shared/util';
import { pushModal } from '../../../modals/modalsSlice';
+import {
+ envelopeBudget,
+ trackingBudget,
+ uncategorizedCount,
+} from '../../../queries/queries';
import { useDispatch } from '../../../redux';
import { MobilePageHeader, Page } from '../../Page';
import { PrivacyFilter } from '../../PrivacyFilter';
diff --git a/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx b/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
index c0767dec63..f5b373b75d 100644
--- a/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/CategoryTransactions.tsx
@@ -3,7 +3,6 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { TextOneLine } from '@actual-app/components/text-one-line';
import { View } from '@actual-app/components/view';
-import * as queries from 'loot-core/client/queries';
import { listen } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
@@ -13,6 +12,7 @@ import {
type TransactionEntity,
} from 'loot-core/types/models';
+import * as queries from '../../../queries/queries';
import { useDispatch } from '../../../redux';
import { MobilePageHeader, Page } from '../../Page';
import { MobileBackButton } from '../MobileBackButton';
diff --git a/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.tsx b/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.tsx
index 740a674a33..0cc2d3928d 100644
--- a/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/ExpenseCategoryListItem.tsx
@@ -9,7 +9,6 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { envelopeBudget, trackingBudget } from 'loot-core/client/queries';
import { type BudgetType } from 'loot-core/server/prefs';
import * as monthUtils from 'loot-core/shared/months';
import { groupById, integerToCurrency } from 'loot-core/shared/util';
@@ -20,6 +19,7 @@ import { useNavigate } from '../../../hooks/useNavigate';
import { useSyncedPref } from '../../../hooks/useSyncedPref';
import { useUndo } from '../../../hooks/useUndo';
import { collapseModals, pushModal } from '../../../modals/modalsSlice';
+import { envelopeBudget, trackingBudget } from '../../../queries/queries';
import { useDispatch } from '../../../redux';
import { useSheetValue } from '../../spreadsheet/useSheetValue';
diff --git a/packages/desktop-client/src/components/mobile/budget/ExpenseGroupListItem.tsx b/packages/desktop-client/src/components/mobile/budget/ExpenseGroupListItem.tsx
index b790111a08..6428d1ac22 100644
--- a/packages/desktop-client/src/components/mobile/budget/ExpenseGroupListItem.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/ExpenseGroupListItem.tsx
@@ -12,7 +12,6 @@ import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
import { AutoTextSize } from 'auto-text-size';
-import { envelopeBudget, trackingBudget } from 'loot-core/client/queries';
import * as monthUtils from 'loot-core/shared/months';
import {
type CategoryEntity,
@@ -20,6 +19,7 @@ import {
} from 'loot-core/types/models';
import { useSyncedPref } from '../../../hooks/useSyncedPref';
+import { envelopeBudget, trackingBudget } from '../../../queries/queries';
import { PrivacyFilter } from '../../PrivacyFilter';
import { CellValue } from '../../spreadsheet/CellValue';
import { useFormat } from '../../spreadsheet/useFormat';
diff --git a/packages/desktop-client/src/components/mobile/budget/IncomeCategoryListItem.tsx b/packages/desktop-client/src/components/mobile/budget/IncomeCategoryListItem.tsx
index 942bfb7f84..adf1a69a4f 100644
--- a/packages/desktop-client/src/components/mobile/budget/IncomeCategoryListItem.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/IncomeCategoryListItem.tsx
@@ -9,10 +9,11 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { envelopeBudget, trackingBudget } from 'loot-core/client/queries';
import * as monthUtils from 'loot-core/shared/months';
import { type CategoryEntity } from 'loot-core/types/models';
+import { envelopeBudget, trackingBudget } from '../../../queries/queries';
+
import { BalanceCell } from './BalanceCell';
import { BudgetCell } from './BudgetCell';
import { getColumnWidth, ROW_HEIGHT } from './BudgetTable';
diff --git a/packages/desktop-client/src/components/mobile/budget/IncomeGroup.tsx b/packages/desktop-client/src/components/mobile/budget/IncomeGroup.tsx
index 21b5fa4a04..711c624489 100644
--- a/packages/desktop-client/src/components/mobile/budget/IncomeGroup.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/IncomeGroup.tsx
@@ -13,10 +13,10 @@ import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
import { AutoTextSize } from 'auto-text-size';
-import { envelopeBudget, trackingBudget } from 'loot-core/client/queries';
import * as monthUtils from 'loot-core/shared/months';
import { type CategoryGroupEntity } from 'loot-core/types/models';
+import { envelopeBudget, trackingBudget } from '../../../queries/queries';
import { PrivacyFilter } from '../../PrivacyFilter';
import { CellValue } from '../../spreadsheet/CellValue';
import { useFormat } from '../../spreadsheet/useFormat';
diff --git a/packages/desktop-client/src/components/mobile/budget/index.tsx b/packages/desktop-client/src/components/mobile/budget/index.tsx
index a89027d9be..1a08cd75ac 100644
--- a/packages/desktop-client/src/components/mobile/budget/index.tsx
+++ b/packages/desktop-client/src/components/mobile/budget/index.tsx
@@ -5,7 +5,6 @@ import { AnimatedLoading } from '@actual-app/components/icons/AnimatedLoading';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
@@ -30,6 +29,7 @@ import { BudgetTable } from './BudgetTable';
import { useCategories } from '@desktop-client/hooks/useCategories';
import { useLocale } from '@desktop-client/hooks/useLocale';
import { useLocalPref } from '@desktop-client/hooks/useLocalPref';
+import { useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
function isBudgetType(input?: string): input is 'envelope' | 'tracking' {
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.jsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.jsx
index 094f2b7cbe..f04c763331 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.jsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.jsx
@@ -30,10 +30,9 @@ import {
isValid as isValidDate,
} from 'date-fns';
-import * as Platform from 'loot-core/client/platform';
-import { aqlQuery } from 'loot-core/client/query-helpers';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
+import * as Platform from 'loot-core/shared/platform';
import { q } from 'loot-core/shared/query';
import {
ungroupTransactions,
@@ -55,6 +54,7 @@ import {
} from 'loot-core/shared/util';
import { pushModal } from '../../../modals/modalsSlice';
+import { aqlQuery } from '../../../queries/aqlQuery';
import { setLastTransaction } from '../../../queries/queriesSlice';
import { useSelector, useDispatch } from '../../../redux';
import { MobilePageHeader, Page } from '../../Page';
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
index 25cbf5a8be..81ab90f984 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionList.tsx
@@ -29,9 +29,9 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { validForTransfer } from 'loot-core/client/transfer';
import * as monthUtils from 'loot-core/shared/months';
import { isPreviewId } from 'loot-core/shared/transactions';
+import { validForTransfer } from 'loot-core/shared/transfer';
import { groupById, integerToCurrency } from 'loot-core/shared/util';
import {
type AccountEntity,
diff --git a/packages/desktop-client/src/components/modals/EditRuleModal.jsx b/packages/desktop-client/src/components/modals/EditRuleModal.jsx
index 4f4b82a76a..2341d9163d 100644
--- a/packages/desktop-client/src/components/modals/EditRuleModal.jsx
+++ b/packages/desktop-client/src/components/modals/EditRuleModal.jsx
@@ -23,8 +23,6 @@ import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
import { v4 as uuid } from 'uuid';
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { enableUndo, disableUndo } from 'loot-core/client/undo';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
@@ -46,8 +44,10 @@ import {
amountToInteger,
} from 'loot-core/shared/util';
+import { aqlQuery } from '../../queries/aqlQuery';
import { initiallyLoadPayees } from '../../queries/queriesSlice';
import { useDispatch } from '../../redux';
+import { enableUndo, disableUndo } from '../../undo';
import { Modal, ModalCloseButton, ModalHeader } from '../common/Modal';
import { StatusBadge } from '../schedules/StatusBadge';
import { SimpleTransactionsTable } from '../transactions/SimpleTransactionsTable';
diff --git a/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.tsx b/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.tsx
index 9b33846f75..acafca1bc3 100644
--- a/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/EnvelopeBalanceMenuModal.tsx
@@ -6,9 +6,8 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { envelopeBudget } from 'loot-core/client/queries';
-
import { type Modal as ModalType } from '../../modals/modalsSlice';
+import { envelopeBudget } from '../../queries/queries';
import {
BalanceWithCarryover,
CarryoverIndicator,
diff --git a/packages/desktop-client/src/components/modals/EnvelopeBudgetMenuModal.tsx b/packages/desktop-client/src/components/modals/EnvelopeBudgetMenuModal.tsx
index d43e347d92..799739e824 100644
--- a/packages/desktop-client/src/components/modals/EnvelopeBudgetMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/EnvelopeBudgetMenuModal.tsx
@@ -6,11 +6,11 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import * as Platform from 'loot-core/client/platform';
-import { envelopeBudget } from 'loot-core/client/queries';
+import * as Platform from 'loot-core/shared/platform';
import { amountToInteger, integerToAmount } from 'loot-core/shared/util';
import { type Modal as ModalType } from '../../modals/modalsSlice';
+import { envelopeBudget } from '../../queries/queries';
import { BudgetMenu } from '../budget/envelope/BudgetMenu';
import { useEnvelopeSheetValue } from '../budget/envelope/EnvelopeBudgetComponents';
import {
diff --git a/packages/desktop-client/src/components/modals/EnvelopeBudgetSummaryModal.tsx b/packages/desktop-client/src/components/modals/EnvelopeBudgetSummaryModal.tsx
index 94d179a09c..33e90bfaba 100644
--- a/packages/desktop-client/src/components/modals/EnvelopeBudgetSummaryModal.tsx
+++ b/packages/desktop-client/src/components/modals/EnvelopeBudgetSummaryModal.tsx
@@ -3,7 +3,6 @@ import { useTranslation } from 'react-i18next';
import { styles } from '@actual-app/components/styles';
-import { envelopeBudget } from 'loot-core/client/queries';
import { format, sheetForMonth, prevMonth } from 'loot-core/shared/months';
import { groupById, integerToCurrency } from 'loot-core/shared/util';
@@ -12,6 +11,7 @@ import {
type Modal as ModalType,
pushModal,
} from '../../modals/modalsSlice';
+import { envelopeBudget } from '../../queries/queries';
import { useDispatch } from '../../redux';
import { ToBudgetAmount } from '../budget/envelope/budgetsummary/ToBudgetAmount';
import { TotalsList } from '../budget/envelope/budgetsummary/TotalsList';
diff --git a/packages/desktop-client/src/components/modals/HoldBufferModal.tsx b/packages/desktop-client/src/components/modals/HoldBufferModal.tsx
index d9109ed7f3..b1dcfed620 100644
--- a/packages/desktop-client/src/components/modals/HoldBufferModal.tsx
+++ b/packages/desktop-client/src/components/modals/HoldBufferModal.tsx
@@ -6,9 +6,8 @@ import { InitialFocus } from '@actual-app/components/initial-focus';
import { styles } from '@actual-app/components/styles';
import { View } from '@actual-app/components/view';
-import { envelopeBudget } from 'loot-core/client/queries';
-
import { type Modal as ModalType } from '../../modals/modalsSlice';
+import { envelopeBudget } from '../../queries/queries';
import { useEnvelopeSheetValue } from '../budget/envelope/EnvelopeBudgetComponents';
import { Modal, ModalCloseButton, ModalHeader } from '../common/Modal';
import { FieldLabel } from '../mobile/MobileForms';
diff --git a/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx b/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx
index cbe9747275..a32ddac593 100644
--- a/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx
+++ b/packages/desktop-client/src/components/modals/KeyboardShortcutModal.tsx
@@ -5,7 +5,7 @@ import { useLocation } from 'react-router-dom';
import { Text } from '@actual-app/components/text';
import { View } from '@actual-app/components/view';
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
import { Modal, ModalCloseButton, ModalHeader } from '../common/Modal';
diff --git a/packages/desktop-client/src/components/modals/TrackingBalanceMenuModal.tsx b/packages/desktop-client/src/components/modals/TrackingBalanceMenuModal.tsx
index 7398dd8a9d..00e0113261 100644
--- a/packages/desktop-client/src/components/modals/TrackingBalanceMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/TrackingBalanceMenuModal.tsx
@@ -6,9 +6,8 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { trackingBudget } from 'loot-core/client/queries';
-
import { type Modal as ModalType } from '../../modals/modalsSlice';
+import { trackingBudget } from '../../queries/queries';
import {
BalanceWithCarryover,
CarryoverIndicator,
diff --git a/packages/desktop-client/src/components/modals/TrackingBudgetMenuModal.tsx b/packages/desktop-client/src/components/modals/TrackingBudgetMenuModal.tsx
index c36a58ceca..07a2bb701a 100644
--- a/packages/desktop-client/src/components/modals/TrackingBudgetMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/TrackingBudgetMenuModal.tsx
@@ -6,11 +6,11 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import * as Platform from 'loot-core/client/platform';
-import { trackingBudget } from 'loot-core/client/queries';
+import * as Platform from 'loot-core/shared/platform';
import { amountToInteger, integerToAmount } from 'loot-core/shared/util';
import { type Modal as ModalType } from '../../modals/modalsSlice';
+import { trackingBudget } from '../../queries/queries';
import { BudgetMenu } from '../budget/tracking/BudgetMenu';
import { useTrackingSheetValue } from '../budget/tracking/TrackingBudgetComponents';
import {
diff --git a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx b/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
index 6dc44332ab..fb31483397 100644
--- a/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
+++ b/packages/desktop-client/src/components/reports/reports/CustomReport.tsx
@@ -11,7 +11,6 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import * as d from 'date-fns';
-import { calculateHasWarning } from 'loot-core/client/reports';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { amountToCurrency } from 'loot-core/shared/util';
@@ -53,7 +52,7 @@ import { setSessionReport } from '../setSessionReport';
import { createCustomSpreadsheet } from '../spreadsheets/custom-spreadsheet';
import { createGroupedSpreadsheet } from '../spreadsheets/grouped-spreadsheet';
import { useReport } from '../useReport';
-import { fromDateRepr } from '../util';
+import { calculateHasWarning, fromDateRepr } from '../util';
import { useAccounts } from '@desktop-client/hooks/useAccounts';
import { useCategories } from '@desktop-client/hooks/useCategories';
diff --git a/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx b/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx
index 41646a8c7b..b27c7a22a6 100644
--- a/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx
+++ b/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx
@@ -8,7 +8,6 @@ import { theme } from '@actual-app/components/theme';
import { Tooltip } from '@actual-app/components/tooltip';
import { View } from '@actual-app/components/view';
-import { calculateHasWarning } from 'loot-core/client/reports';
import { send, sendCatch } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { type CustomReportEntity } from 'loot-core/types/models';
@@ -18,6 +17,7 @@ import { useDispatch } from '../../../redux';
import { DateRange } from '../DateRange';
import { ReportCard } from '../ReportCard';
import { ReportCardName } from '../ReportCardName';
+import { calculateHasWarning } from '../util';
import { GetCardData } from './GetCardData';
import { MissingReportCard } from './MissingReportCard';
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/calendar-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/calendar-spreadsheet.ts
index b4e0409229..0f0c52728e 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/calendar-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/calendar-spreadsheet.ts
@@ -1,13 +1,15 @@
import * as d from 'date-fns';
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { type useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
import { type RuleConditionEntity } from 'loot-core/types/models';
import { type SyncedPrefs } from 'loot-core/types/prefs';
+import { aqlQuery } from '../../../queries/aqlQuery';
+
+import { type useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+
export type CalendarDataType = {
date: Date;
incomeValue: number;
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx b/packages/desktop-client/src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx
index f98e4824dd..b02b06dd8c 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx
+++ b/packages/desktop-client/src/components/reports/spreadsheets/cash-flow-spreadsheet.tsx
@@ -4,13 +4,13 @@ import { AlignedText } from '@actual-app/components/aligned-text';
import * as d from 'date-fns';
import { t } from 'i18next';
-import { type useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
import { integerToCurrency, integerToAmount } from 'loot-core/shared/util';
import { type RuleConditionEntity } from 'loot-core/types/models';
+import { type useSpreadsheet } from '../../../hooks/useSpreadsheet';
import { runAll, indexCashFlow } from '../util';
export function simpleCashFlow(
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts
index ed8d55994a..792163ab18 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/custom-spreadsheet.ts
@@ -1,7 +1,5 @@
import * as d from 'date-fns';
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { type useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { integerToAmount } from 'loot-core/shared/util';
@@ -19,6 +17,7 @@ import {
} from 'loot-core/types/models';
import { type SyncedPrefs } from 'loot-core/types/prefs';
+import { aqlQuery } from '../../../queries/aqlQuery';
import {
categoryLists,
groupBySelections,
@@ -34,6 +33,8 @@ import { makeQuery } from './makeQuery';
import { recalculate } from './recalculate';
import { sortData } from './sortData';
+import { type useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+
export type createCustomSpreadsheetProps = {
startDate: string;
endDate: string;
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 42d7205b9a..7cbb624ae8 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/grouped-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/grouped-spreadsheet.ts
@@ -1,9 +1,8 @@
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { type useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { type GroupedEntity } from 'loot-core/types/models';
+import { aqlQuery } from '../../../queries/aqlQuery';
import {
categoryLists,
type QueryDataEntity,
@@ -16,6 +15,8 @@ import { makeQuery } from './makeQuery';
import { recalculate } from './recalculate';
import { sortData } from './sortData';
+import { type useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+
export function createGroupedSpreadsheet({
startDate,
endDate,
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
index 59530d0bae..6ea2e7225b 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/net-worth-spreadsheet.ts
@@ -1,8 +1,6 @@
import * as d from 'date-fns';
import keyBy from 'lodash/keyBy';
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { type useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
@@ -16,6 +14,10 @@ import {
type RuleConditionEntity,
} from 'loot-core/types/models';
+import { aqlQuery } from '../../../queries/aqlQuery';
+
+import { type useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+
type Balance = {
date: string;
amount: number;
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts
index 06cb3849be..3d9b42d771 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts
@@ -1,8 +1,6 @@
// @ts-strict-ignore
import keyBy from 'lodash/keyBy';
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { type useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
@@ -13,8 +11,12 @@ import {
type SpendingEntity,
} from 'loot-core/types/models';
+import { aqlQuery } from '../../../queries/aqlQuery';
+
import { makeQuery } from './makeQuery';
+import { type useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+
type createSpendingSpreadsheetProps = {
conditions?: RuleConditionEntity[];
conditionsOp?: string;
diff --git a/packages/desktop-client/src/components/reports/spreadsheets/summary-spreadsheet.ts b/packages/desktop-client/src/components/reports/spreadsheets/summary-spreadsheet.ts
index ebd7212c33..3f230565c2 100644
--- a/packages/desktop-client/src/components/reports/spreadsheets/summary-spreadsheet.ts
+++ b/packages/desktop-client/src/components/reports/spreadsheets/summary-spreadsheet.ts
@@ -1,7 +1,5 @@
import * as d from 'date-fns';
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { type useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
@@ -10,6 +8,10 @@ import {
type RuleConditionEntity,
} from 'loot-core/types/models';
+import { aqlQuery } from '../../../queries/aqlQuery';
+
+import { type useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+
export function summarySpreadsheet(
start: string,
end: string,
diff --git a/packages/desktop-client/src/components/reports/useReport.ts b/packages/desktop-client/src/components/reports/useReport.ts
index 4e82b68847..0bc60ff7c7 100644
--- a/packages/desktop-client/src/components/reports/useReport.ts
+++ b/packages/desktop-client/src/components/reports/useReport.ts
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
-import { useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
+import { useSpreadsheet } from '../../hooks/useSpreadsheet';
export function useReport<T>(
sheetName: string,
diff --git a/packages/desktop-client/src/components/reports/util.ts b/packages/desktop-client/src/components/reports/util.ts
index d7c4c45c1a..02afebb056 100644
--- a/packages/desktop-client/src/components/reports/util.ts
+++ b/packages/desktop-client/src/components/reports/util.ts
@@ -1,6 +1,13 @@
// @ts-strict-ignore
-import { aqlQuery } from 'loot-core/client/query-helpers';
import type { Query } from 'loot-core/shared/query';
+import type {
+ RuleConditionEntity,
+ CategoryEntity,
+ AccountEntity,
+ PayeeEntity,
+} from 'loot-core/types/models';
+
+import { aqlQuery } from '../../queries/aqlQuery';
export function fromDateRepr(date: string): string {
return date.slice(0, 7);
@@ -29,3 +36,85 @@ export function indexCashFlow<
});
return results;
}
+
+/**
+ * Checks if the given conditions have issues
+ * (i.e. non-existing category/payee/account being used).
+ */
+
+export function calculateHasWarning(
+ conditions: RuleConditionEntity[],
+ {
+ categories,
+ accounts,
+ payees,
+ }: {
+ categories: CategoryEntity[];
+ accounts: AccountEntity[];
+ payees: PayeeEntity[];
+ },
+) {
+ const categoryIds = new Set(categories.map(({ id }) => id));
+ const payeeIds = new Set(payees.map(({ id }) => id));
+ const accountIds = new Set(accounts.map(({ id }) => id));
+
+ if (!conditions) {
+ return false;
+ }
+
+ for (const cond of conditions) {
+ const { field, value, op } = cond;
+ const isMultiCondition = Array.isArray(value);
+ const isSupportedSingleCondition = ['is', 'isNot'].includes(op);
+
+ // Regex and other more complicated operations are not supported
+ if (!isSupportedSingleCondition && !isMultiCondition) {
+ continue;
+ }
+
+ // Empty value.. we can skip
+ if (!isMultiCondition && !value) {
+ continue;
+ }
+
+ switch (field) {
+ case 'account':
+ if (isMultiCondition) {
+ if (value.find(val => !accountIds.has(val))) {
+ return true;
+ }
+ break;
+ }
+
+ if (!accountIds.has(value)) {
+ return true;
+ }
+ break;
+ case 'payee':
+ if (isMultiCondition) {
+ if (value.find(val => !payeeIds.has(val))) {
+ return true;
+ }
+ break;
+ }
+
+ if (!payeeIds.has(value)) {
+ return true;
+ }
+ break;
+ case 'category':
+ if (isMultiCondition) {
+ if (value.find(val => !categoryIds.has(val))) {
+ return true;
+ }
+ break;
+ }
+
+ if (!categoryIds.has(value)) {
+ return true;
+ }
+ break;
+ }
+ }
+ return false;
+}
diff --git a/packages/desktop-client/src/components/schedules/DiscoverSchedules.tsx b/packages/desktop-client/src/components/schedules/DiscoverSchedules.tsx
index 7d42bb3530..a8874fc6c6 100644
--- a/packages/desktop-client/src/components/schedules/DiscoverSchedules.tsx
+++ b/packages/desktop-client/src/components/schedules/DiscoverSchedules.tsx
@@ -8,12 +8,12 @@ import { Stack } from '@actual-app/components/stack';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import { aqlQuery } from 'loot-core/client/query-helpers';
import { send } from 'loot-core/platform/client/fetch';
import { q } from 'loot-core/shared/query';
import { getRecurringDescription } from 'loot-core/shared/schedules';
import type { DiscoverScheduleEntity } from 'loot-core/types/models';
+import { aqlQuery } from '../../queries/aqlQuery';
import { Modal, ModalCloseButton, ModalHeader } from '../common/Modal';
import { Table, TableHeader, Row, Field, SelectCell } from '../table';
import { DisplayId } from '../util/DisplayId';
diff --git a/packages/desktop-client/src/components/schedules/ScheduleDetails.tsx b/packages/desktop-client/src/components/schedules/ScheduleDetails.tsx
index 2247f7bcce..bcb3ec6ff3 100644
--- a/packages/desktop-client/src/components/schedules/ScheduleDetails.tsx
+++ b/packages/desktop-client/src/components/schedules/ScheduleDetails.tsx
@@ -10,7 +10,6 @@ import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
import { t } from 'i18next';
-import { aqlQuery, liveQuery } from 'loot-core/client/query-helpers';
import { send, sendCatch } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
@@ -23,6 +22,8 @@ import {
} from 'loot-core/types/models';
import { type Modal as ModalType, pushModal } from '../../modals/modalsSlice';
+import { aqlQuery } from '../../queries/aqlQuery';
+import { liveQuery } from '../../queries/liveQuery';
import { getPayeesById } from '../../queries/queriesSlice';
import { useDispatch } from '../../redux';
import { AccountAutocomplete } from '../autocomplete/AccountAutocomplete';
diff --git a/packages/desktop-client/src/components/sidebar/Account.tsx b/packages/desktop-client/src/components/sidebar/Account.tsx
index 6b5946c543..22cb3befee 100644
--- a/packages/desktop-client/src/components/sidebar/Account.tsx
+++ b/packages/desktop-client/src/components/sidebar/Account.tsx
@@ -13,7 +13,7 @@ import { Tooltip } from '@actual-app/components/tooltip';
import { View } from '@actual-app/components/view';
import { css, cx } from '@emotion/css';
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
import { type AccountEntity } from 'loot-core/types/models';
import { openAccountCloseModal } from '../../modals/modalsSlice';
diff --git a/packages/desktop-client/src/components/sidebar/Accounts.tsx b/packages/desktop-client/src/components/sidebar/Accounts.tsx
index 423a2175fa..52c94173a4 100644
--- a/packages/desktop-client/src/components/sidebar/Accounts.tsx
+++ b/packages/desktop-client/src/components/sidebar/Accounts.tsx
@@ -4,10 +4,10 @@ import { useTranslation } from 'react-i18next';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import * as queries from 'loot-core/client/queries';
import { type AccountEntity } from 'loot-core/types/models';
import { moveAccount } from '../../accounts/accountsSlice';
+import * as queries from '../../queries/queries';
import { useSelector, useDispatch } from '../../redux';
import { Account } from './Account';
diff --git a/packages/desktop-client/src/components/sidebar/BudgetName.tsx b/packages/desktop-client/src/components/sidebar/BudgetName.tsx
index 7ab90da29f..f4231c7f97 100644
--- a/packages/desktop-client/src/components/sidebar/BudgetName.tsx
+++ b/packages/desktop-client/src/components/sidebar/BudgetName.tsx
@@ -11,7 +11,7 @@ import { Text } from '@actual-app/components/text';
import { theme } from '@actual-app/components/theme';
import { View } from '@actual-app/components/view';
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
import { closeBudget } from '../../budgets/budgetsSlice';
import { useDispatch } from '../../redux';
diff --git a/packages/desktop-client/src/components/sidebar/Sidebar.tsx b/packages/desktop-client/src/components/sidebar/Sidebar.tsx
index 3d14660220..96fea37204 100644
--- a/packages/desktop-client/src/components/sidebar/Sidebar.tsx
+++ b/packages/desktop-client/src/components/sidebar/Sidebar.tsx
@@ -9,7 +9,7 @@ import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
import { Resizable } from 're-resizable';
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
import { replaceModal } from '../../modals/modalsSlice';
import { useDispatch } from '../../redux';
diff --git a/packages/desktop-client/src/components/spreadsheet/useSheetValue.ts b/packages/desktop-client/src/components/spreadsheet/useSheetValue.ts
index 4e1998b946..774acccbe9 100644
--- a/packages/desktop-client/src/components/spreadsheet/useSheetValue.ts
+++ b/packages/desktop-client/src/components/spreadsheet/useSheetValue.ts
@@ -1,6 +1,6 @@
import { useState, useRef, useLayoutEffect } from 'react';
-import { useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
+import { useSpreadsheet } from '../../hooks/useSpreadsheet';
import { useSheetName } from './useSheetName';
diff --git a/packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx b/packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx
index 74b957aca8..33b97ee3ee 100644
--- a/packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx
+++ b/packages/desktop-client/src/components/transactions/SelectedTransactionsButton.tsx
@@ -4,13 +4,13 @@ import { useTranslation } from 'react-i18next';
import { Menu } from '@actual-app/components/menu';
-import { validForTransfer } from 'loot-core/client/transfer';
import { q } from 'loot-core/shared/query';
import {
scheduleIsRecurring,
extractScheduleConds,
} from 'loot-core/shared/schedules';
import { isPreviewId } from 'loot-core/shared/transactions';
+import { validForTransfer } from 'loot-core/shared/transfer';
import { type TransactionEntity } from 'loot-core/types/models';
import { pushModal } from '../../modals/modalsSlice';
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
index 4193d9ffc1..b39e58d469 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
@@ -5,7 +5,6 @@ import userEvent from '@testing-library/user-event';
import { format as formatDate, parse as parseDate } from 'date-fns';
import { v4 as uuidv4 } from 'uuid';
-import { SpreadsheetProvider } from 'loot-core/client/SpreadsheetProvider';
import {
generateTransaction,
generateAccount,
@@ -35,6 +34,7 @@ import { TransactionTable } from './TransactionsTable';
import { SchedulesProvider } from '@desktop-client/hooks/useCachedSchedules';
import { SelectedProviderWithItems } from '@desktop-client/hooks/useSelected';
import { SplitsExpandedProvider } from '@desktop-client/hooks/useSplitsExpanded';
+import { SpreadsheetProvider } from '@desktop-client/hooks/useSpreadsheet';
vi.mock('loot-core/platform/client/fetch');
vi.mock('../../hooks/useFeatureFlag', () => ({
diff --git a/packages/desktop-client/src/global-events.ts b/packages/desktop-client/src/global-events.ts
index 7dcc2a7033..8c169dd543 100644
--- a/packages/desktop-client/src/global-events.ts
+++ b/packages/desktop-client/src/global-events.ts
@@ -1,5 +1,4 @@
// @ts-strict-ignore
-import * as sharedListeners from 'loot-core/client/shared-listeners';
import { listen } from 'loot-core/platform/client/fetch';
import * as undo from 'loot-core/platform/client/undo';
@@ -13,6 +12,7 @@ import {
import { loadPrefs } from './prefs/prefsSlice';
import { getAccounts, getCategories, getPayees } from './queries/queriesSlice';
import { type AppStore } from './redux/store';
+import * as syncEvents from './sync-events';
export function handleGlobalEvents(store: AppStore) {
const unlistenServerError = listen('server-error', () => {
@@ -43,7 +43,7 @@ export function handleGlobalEvents(store: AppStore) {
);
});
- const unlistenSync = sharedListeners.listenForSyncEvent(store);
+ const unlistenSync = syncEvents.listenForSyncEvent(store);
const unlistenUndo = listen('undo-event', undoState => {
const { tables, undoTag } = undoState;
diff --git a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
index f100c0389d..c100b623b4 100644
--- a/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/useAccountPreviewTransactions.ts
@@ -1,6 +1,5 @@
import { useCallback, useMemo } from 'react';
-import { accountBalance } from 'loot-core/client/queries';
import { groupById } from 'loot-core/shared/util';
import {
type ScheduleEntity,
@@ -14,6 +13,7 @@ import { usePayees } from './usePayees';
import { usePreviewTransactions } from './usePreviewTransactions';
import { useSheetValue } from '@desktop-client/components/spreadsheet/useSheetValue';
+import { accountBalance } from '@desktop-client/queries/queries';
type UseAccountPreviewTransactionsProps = {
accountId?: AccountEntity['id'] | undefined;
diff --git a/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts b/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
index da7a8e4b48..28841538c3 100644
--- a/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/useCategoryPreviewTransactions.ts
@@ -1,6 +1,5 @@
import { useCallback, useMemo } from 'react';
-import { categoryBalance } from 'loot-core/client/queries';
import * as monthUtils from 'loot-core/shared/months';
import {
type ScheduleEntity,
@@ -12,6 +11,7 @@ import { useCategoryScheduleGoalTemplates } from './useCategoryScheduleGoalTempl
import { usePreviewTransactions } from './usePreviewTransactions';
import { useSheetValue } from '@desktop-client/components/spreadsheet/useSheetValue';
+import { categoryBalance } from '@desktop-client/queries/queries';
type UseCategoryPreviewTransactionsProps = {
categoryId: CategoryEntity['id'];
diff --git a/packages/desktop-client/src/hooks/useDashboard.ts b/packages/desktop-client/src/hooks/useDashboard.ts
index 4bf88ba965..06441ec405 100644
--- a/packages/desktop-client/src/hooks/useDashboard.ts
+++ b/packages/desktop-client/src/hooks/useDashboard.ts
@@ -1,9 +1,10 @@
import { useMemo } from 'react';
-import { useQuery } from 'loot-core/client/query-hooks';
import { q } from 'loot-core/shared/query';
import { type Widget } from 'loot-core/types/models';
+import { useQuery } from './useQuery';
+
export function useDashboard() {
const { data: queryData, isLoading } = useQuery<Widget>(
() => q('dashboard').select('*'),
diff --git a/packages/desktop-client/src/hooks/useNotes.ts b/packages/desktop-client/src/hooks/useNotes.ts
index 29789e2ffd..c88a674857 100644
--- a/packages/desktop-client/src/hooks/useNotes.ts
+++ b/packages/desktop-client/src/hooks/useNotes.ts
@@ -1,9 +1,10 @@
import { useMemo } from 'react';
-import { useQuery } from 'loot-core/client/query-hooks';
import { q } from 'loot-core/shared/query';
import { type NoteEntity } from 'loot-core/types/models';
+import { useQuery } from './useQuery';
+
export function useNotes(id: string) {
const { data } = useQuery<NoteEntity>(
() => q('notes').filter({ id }).select('*'),
diff --git a/packages/desktop-client/src/hooks/useOverspentCategories.ts b/packages/desktop-client/src/hooks/useOverspentCategories.ts
index 9c1f38e09a..db9f46c9a0 100644
--- a/packages/desktop-client/src/hooks/useOverspentCategories.ts
+++ b/packages/desktop-client/src/hooks/useOverspentCategories.ts
@@ -1,11 +1,14 @@
import { useEffect, useMemo, useState } from 'react';
-import { envelopeBudget, trackingBudget } from 'loot-core/client/queries';
-import { useSpreadsheet } from 'loot-core/client/SpreadsheetProvider';
import * as monthUtils from 'loot-core/shared/months';
-import { useCategories } from './useCategories';
-import { useSyncedPref } from './useSyncedPref';
+import { useCategories } from '@desktop-client/hooks/useCategories';
+import { useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';
+import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';
+import {
+ envelopeBudget,
+ trackingBudget,
+} from '@desktop-client/queries/queries';
type UseOverspentCategoriesProps = {
month: string;
diff --git a/packages/desktop-client/src/hooks/usePreviewTransactions.ts b/packages/desktop-client/src/hooks/usePreviewTransactions.ts
index 3db5cb2ba9..9a246624ee 100644
--- a/packages/desktop-client/src/hooks/usePreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/usePreviewTransactions.ts
@@ -2,7 +2,6 @@ import { useEffect, useRef, useState, useMemo, useCallback } from 'react';
import * as d from 'date-fns';
-import { pagedQuery, type PagedQuery } from 'loot-core/client/query-helpers';
import { send } from 'loot-core/platform/client/fetch';
import { currentDay, addDays, parseDate } from 'loot-core/shared/months';
import { type Query } from 'loot-core/shared/query';
@@ -24,6 +23,11 @@ import { useCachedSchedules } from './useCachedSchedules';
import { type ScheduleStatuses } from './useSchedules';
import { useSyncedPref } from './useSyncedPref';
+import {
+ pagedQuery,
+ type PagedQuery,
+} from '@desktop-client/queries/pagedQuery';
+
// Mirrors the `splits` AQL option from the server
type TransactionSplitsOption = 'all' | 'inline' | 'grouped' | 'none';
diff --git a/packages/loot-core/src/client/query-hooks.ts b/packages/desktop-client/src/hooks/useQuery.ts
similarity index 92%
rename from packages/loot-core/src/client/query-hooks.ts
rename to packages/desktop-client/src/hooks/useQuery.ts
index 02a66e412d..7ccaa33d2f 100644
--- a/packages/loot-core/src/client/query-hooks.ts
+++ b/packages/desktop-client/src/hooks/useQuery.ts
@@ -1,8 +1,8 @@
import { useState, useMemo, useEffect, type DependencyList } from 'react';
-import { type Query } from '../shared/query';
+import { type Query } from 'loot-core/shared/query';
-import { liveQuery, type LiveQuery } from './query-helpers';
+import { liveQuery, type LiveQuery } from '../queries/liveQuery';
type UseQueryResult<Response> = {
data: null | ReadonlyArray<Response>;
diff --git a/packages/desktop-client/src/hooks/useReports.ts b/packages/desktop-client/src/hooks/useReports.ts
index 0f9280a5d5..81f782b7fc 100644
--- a/packages/desktop-client/src/hooks/useReports.ts
+++ b/packages/desktop-client/src/hooks/useReports.ts
@@ -1,12 +1,13 @@
import { useMemo } from 'react';
-import { useQuery } from 'loot-core/client/query-hooks';
import { q } from 'loot-core/shared/query';
import {
type CustomReportData,
type CustomReportEntity,
} from 'loot-core/types/models';
+import { useQuery } from './useQuery';
+
function toJS(rows: CustomReportData[]) {
const reports: CustomReportEntity[] = rows.map(row => {
const report: CustomReportEntity = {
diff --git a/packages/desktop-client/src/hooks/useSchedules.ts b/packages/desktop-client/src/hooks/useSchedules.ts
index e538235fbe..fe42ea1115 100644
--- a/packages/desktop-client/src/hooks/useSchedules.ts
+++ b/packages/desktop-client/src/hooks/useSchedules.ts
@@ -1,7 +1,5 @@
import { useState, useRef, useEffect } from 'react';
-import { accountFilter } from 'loot-core/client/queries';
-import { liveQuery, type LiveQuery } from 'loot-core/client/query-helpers';
import { q, type Query } from 'loot-core/shared/query';
import {
getStatus,
@@ -14,6 +12,9 @@ import type {
TransactionEntity,
} from 'loot-core/types/models';
+import { liveQuery, type LiveQuery } from '../queries/liveQuery';
+import { accountFilter } from '../queries/queries';
+
import { useSyncedPref } from './useSyncedPref';
export type ScheduleStatusType = ReturnType<typeof getStatus>;
diff --git a/packages/loot-core/src/client/SpreadsheetProvider.tsx b/packages/desktop-client/src/hooks/useSpreadsheet.tsx
similarity index 95%
rename from packages/loot-core/src/client/SpreadsheetProvider.tsx
rename to packages/desktop-client/src/hooks/useSpreadsheet.tsx
index bbd6dcbfba..3c96daff91 100644
--- a/packages/loot-core/src/client/SpreadsheetProvider.tsx
+++ b/packages/desktop-client/src/hooks/useSpreadsheet.tsx
@@ -8,9 +8,8 @@ import {
import { LRUCache } from 'lru-cache';
-import { listen, send } from '../platform/client/fetch';
-import { type Node } from '../server/spreadsheet/spreadsheet';
-import { type Query } from '../shared/query';
+import { listen, send } from 'loot-core/platform/client/fetch';
+import { type Query } from 'loot-core/shared/query';
type SpreadsheetContextValue = ReturnType<typeof makeSpreadsheet>;
const SpreadsheetContext = createContext<SpreadsheetContextValue | undefined>(
@@ -28,7 +27,7 @@ export function useSpreadsheet() {
// TODO: Make this generic and replace the Binding type in the desktop-client package.
type Binding = string | { name: string; query?: Query | undefined };
-type CellCacheValue = { name: string; value: Node['value'] | null };
+type CellCacheValue = { name: string; value: string | number | boolean | null };
type CellCache = { [name: string]: Promise<CellCacheValue> | null };
type CellObserverCallback = (node: CellCacheValue) => void;
type CellObservers = { [name: string]: CellObserverCallback[] };
diff --git a/packages/desktop-client/src/hooks/useTransactionBatchActions.ts b/packages/desktop-client/src/hooks/useTransactionBatchActions.ts
index 5b0385047f..d58d0c1d74 100644
--- a/packages/desktop-client/src/hooks/useTransactionBatchActions.ts
+++ b/packages/desktop-client/src/hooks/useTransactionBatchActions.ts
@@ -1,5 +1,3 @@
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { validForTransfer } from 'loot-core/client/transfer';
import { send } from 'loot-core/platform/client/fetch';
import * as monthUtils from 'loot-core/shared/months';
import { q } from 'loot-core/shared/query';
@@ -10,6 +8,7 @@ import {
ungroupTransactions,
updateTransaction,
} from 'loot-core/shared/transactions';
+import { validForTransfer } from 'loot-core/shared/transfer';
import { applyChanges, type Diff } from 'loot-core/shared/util';
import {
type PayeeEntity,
@@ -19,6 +18,7 @@ import {
} from 'loot-core/types/models';
import { pushModal } from '../modals/modalsSlice';
+import { aqlQuery } from '../queries/aqlQuery';
import { useDispatch } from '../redux';
type BatchEditProps = {
diff --git a/packages/desktop-client/src/hooks/useTransactionFilters.ts b/packages/desktop-client/src/hooks/useTransactionFilters.ts
index dd1d1de041..efb31a5fb5 100644
--- a/packages/desktop-client/src/hooks/useTransactionFilters.ts
+++ b/packages/desktop-client/src/hooks/useTransactionFilters.ts
@@ -1,10 +1,11 @@
// @ts-strict-ignore
import { useMemo } from 'react';
-import { useQuery } from 'loot-core/client/query-hooks';
import { q } from 'loot-core/shared/query';
import { type TransactionFilterEntity } from 'loot-core/types/models';
+import { useQuery } from './useQuery';
+
function toJS(rows): TransactionFilterEntity[] {
const filters = rows.map(row => {
return {
diff --git a/packages/desktop-client/src/hooks/useTransactions.ts b/packages/desktop-client/src/hooks/useTransactions.ts
index aad17d5674..cddb9b3c3a 100644
--- a/packages/desktop-client/src/hooks/useTransactions.ts
+++ b/packages/desktop-client/src/hooks/useTransactions.ts
@@ -1,9 +1,10 @@
import { useState, useRef, useEffect, useCallback } from 'react';
-import { type PagedQuery, pagedQuery } from 'loot-core/client/query-helpers';
import type { Query } from 'loot-core/shared/query';
import type { TransactionEntity } from 'loot-core/types/models';
+import { type PagedQuery, pagedQuery } from '../queries/pagedQuery';
+
type UseTransactionsProps = {
/**
* The Query class is immutable so it is important to memoize the query object
diff --git a/packages/desktop-client/src/hooks/useTransactionsSearch.ts b/packages/desktop-client/src/hooks/useTransactionsSearch.ts
index ef787c7f3e..1adeef8163 100644
--- a/packages/desktop-client/src/hooks/useTransactionsSearch.ts
+++ b/packages/desktop-client/src/hooks/useTransactionsSearch.ts
@@ -2,9 +2,10 @@ import { useState, useMemo, useEffect } from 'react';
import { debounce } from 'lodash';
-import * as queries from 'loot-core/client/queries';
import type { Query } from 'loot-core/shared/query';
+import * as queries from '../queries/queries';
+
type UseTransactionsSearchProps = {
updateQuery: (updateFn: (searchQuery: Query) => Query) => void;
resetQuery: () => void;
diff --git a/packages/desktop-client/src/hooks/useUndo.ts b/packages/desktop-client/src/hooks/useUndo.ts
index bf075a380e..704eeee689 100644
--- a/packages/desktop-client/src/hooks/useUndo.ts
+++ b/packages/desktop-client/src/hooks/useUndo.ts
@@ -2,13 +2,12 @@ import { useCallback } from 'react';
import { useResponsive } from '@actual-app/components/hooks/useResponsive';
-import { redo, undo } from 'loot-core/client/undo';
-
import {
addNotification,
type Notification,
} from '../notifications/notificationsSlice';
import { useDispatch } from '../redux';
+import { redo, undo } from '../undo';
type UndoActions = {
undo: () => void;
diff --git a/packages/desktop-client/src/hooks/useWidget.ts b/packages/desktop-client/src/hooks/useWidget.ts
index baf544928d..f62901211d 100644
--- a/packages/desktop-client/src/hooks/useWidget.ts
+++ b/packages/desktop-client/src/hooks/useWidget.ts
@@ -1,9 +1,10 @@
import { useMemo } from 'react';
-import { useQuery } from 'loot-core/client/query-hooks';
import { q } from 'loot-core/shared/query';
import { type Widget } from 'loot-core/types/models';
+import { useQuery } from './useQuery';
+
export function useWidget<W extends Widget>(id: W['id'], type: W['type']) {
const { data = [], isLoading } = useQuery<W>(
() => q('dashboard').filter({ id, type }).select('*'),
diff --git a/packages/desktop-client/src/i18n.ts b/packages/desktop-client/src/i18n.ts
index 5028edfcff..3178665729 100644
--- a/packages/desktop-client/src/i18n.ts
+++ b/packages/desktop-client/src/i18n.ts
@@ -3,7 +3,7 @@ import { initReactI18next } from 'react-i18next';
import i18n from 'i18next';
import resourcesToBackend from 'i18next-resources-to-backend';
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
const languages = import.meta.glob(['/locale/*.json', '!/locale/*_old.json']);
diff --git a/packages/desktop-client/src/index.tsx b/packages/desktop-client/src/index.tsx
index 4087309db0..bd9e6665a9 100644
--- a/packages/desktop-client/src/index.tsx
+++ b/packages/desktop-client/src/index.tsx
@@ -13,8 +13,6 @@ import { Provider } from 'react-redux';
import { bindActionCreators } from '@reduxjs/toolkit';
import { createRoot } from 'react-dom/client';
-import { aqlQuery } from 'loot-core/client/query-helpers';
-import { redo, undo } from 'loot-core/client/undo';
import { send } from 'loot-core/platform/client/fetch';
import { q } from 'loot-core/shared/query';
@@ -30,8 +28,10 @@ import { ServerProvider } from './components/ServerContext';
import * as modalsSlice from './modals/modalsSlice';
import * as notificationsSlice from './notifications/notificationsSlice';
import * as prefsSlice from './prefs/prefsSlice';
+import { aqlQuery } from './queries/aqlQuery';
import * as queriesSlice from './queries/queriesSlice';
import { store } from './redux/store';
+import { redo, undo } from './undo';
import * as usersSlice from './users/usersSlice';
const boundActions = bindActionCreators(
diff --git a/packages/desktop-client/src/queries/aqlQuery.test.ts b/packages/desktop-client/src/queries/aqlQuery.test.ts
new file mode 100644
index 0000000000..794c94a334
--- /dev/null
+++ b/packages/desktop-client/src/queries/aqlQuery.test.ts
@@ -0,0 +1,19 @@
+import * as fetch from 'loot-core/platform/client/fetch';
+import { q } from 'loot-core/shared/query';
+
+import { aqlQuery } from './aqlQuery';
+
+describe('aqlQuery', () => {
+ it('runs an AQL query', async () => {
+ vi.spyOn(fetch, 'send').mockImplementation((name, args) => {
+ if (name === 'query') {
+ return Promise.resolve({ data: args, dependencies: [] });
+ }
+ return Promise.reject(new Error(`Unknown command: ${name}`));
+ });
+
+ const query = q('transactions').select('*');
+ const { data } = await aqlQuery(query);
+ expect(data).toEqual(query.serialize());
+ });
+});
diff --git a/packages/desktop-client/src/queries/aqlQuery.ts b/packages/desktop-client/src/queries/aqlQuery.ts
new file mode 100644
index 0000000000..1ec60e3f41
--- /dev/null
+++ b/packages/desktop-client/src/queries/aqlQuery.ts
@@ -0,0 +1,6 @@
+import { send } from 'loot-core/platform/client/fetch';
+import { type Query } from 'loot-core/shared/query';
+
+export async function aqlQuery(query: Query) {
+ return send('query', query.serialize());
+}
diff --git a/packages/desktop-client/src/queries/liveQuery.test.ts b/packages/desktop-client/src/queries/liveQuery.test.ts
new file mode 100644
index 0000000000..d628c70b43
--- /dev/null
+++ b/packages/desktop-client/src/queries/liveQuery.test.ts
@@ -0,0 +1,288 @@
+// @ts-strict-ignore
+import * as fetch from 'loot-core/platform/client/fetch';
+import { q } from 'loot-core/shared/query';
+import { resetTracer, tracer } from 'loot-core/shared/test-helpers';
+
+import { liveQuery } from './liveQuery';
+
+function wait(n) {
+ return new Promise(resolve => setTimeout(() => resolve(`wait(${n})`), n));
+}
+
+function isCountQuery(query) {
+ if (query.selectExpressions.length === 1) {
+ const select = query.selectExpressions[0];
+ return select.result && select.result.$count === '*';
+ }
+
+ return false;
+}
+
+const eventListeners = new Map();
+
+function clearEventListeners() {
+ eventListeners.clear();
+}
+
+function mockListen(name, listener): () => void {
+ if (!eventListeners.get(name)) {
+ eventListeners.set(name, []);
+ }
+ eventListeners.get(name).push(listener);
+
+ return () => {
+ const arr = eventListeners.get(name);
+ eventListeners.set(
+ name,
+ arr.filter(l => l !== listener),
+ );
+ };
+}
+
+function mockPublishEvent(name, args) {
+ const listeners = eventListeners.get(name);
+ if (listeners) {
+ listeners.forEach(listener => listener(args));
+ }
+}
+
+async function mockSend(name, args, { delay }) {
+ switch (name) {
+ case 'query':
+ const query = args;
+ if (!isCountQuery(query)) {
+ tracer.event('server-query');
+ }
+ if (delay) {
+ await wait(delay);
+ }
+ return { data: query.selectExpressions, dependencies: ['transactions'] };
+ default:
+ throw new Error(`Command not implemented: ${name}`);
+ }
+}
+
+function mockServer({ send = mockSend, listen = mockListen }) {
+ vi.spyOn(fetch, 'send').mockImplementation((name, args) => {
+ return send(name, args, { delay: 0 });
+ });
+ vi.spyOn(fetch, 'listen').mockImplementation(listen);
+}
+
+function clearMockServer() {
+ clearEventListeners();
+ vi.clearAllMocks();
+}
+
+function mockBasicServer(delay?) {
+ mockServer({
+ send: (name, args) => {
+ return mockSend(name, args, { delay });
+ },
+ });
+}
+
+describe('liveQuery', () => {
+ beforeEach(() => {
+ resetTracer();
+ clearMockServer();
+ });
+
+ it(`runs and subscribes to a query`, async () => {
+ mockBasicServer();
+ tracer.start();
+
+ const query = q('transactions').select('*');
+ liveQuery(query, { onData: data => tracer.event('data', data) });
+
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ });
+
+ it(`runs but ignores applied events (onlySync: true)`, async () => {
+ mockBasicServer();
+ tracer.start();
+
+ const query = q('transactions').select('*');
+ liveQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
+
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'applied',
+ tables: ['transactions'],
+ });
+
+ const p = Promise.race([tracer.wait('server-query'), wait(100)]);
+ expect(await p).toEqual('wait(100)');
+ });
+
+ it(`runs and updates with sync events (onlySync: true)`, async () => {
+ mockBasicServer();
+ tracer.start();
+
+ const query = q('transactions').select('*');
+ liveQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
+
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ });
+
+ it(`cancels existing requests`, async () => {
+ let requestId = 0;
+ mockServer({
+ send: async (name, args) => {
+ switch (name) {
+ case 'query':
+ const query = args;
+ if (!isCountQuery(query)) {
+ requestId++;
+ }
+ await wait(500);
+ return { data: requestId, dependencies: ['transactions'] };
+ default:
+ throw new Error(`Command not implemented: ${name}`);
+ }
+ },
+ });
+
+ tracer.start();
+ const query = q('transactions').select('*');
+ const lq = liveQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
+
+ // Users should never call `run` manually but we'll do it to
+ // test
+
+ lq.run();
+ await wait(0);
+ lq.run();
+ await wait(0);
+ lq.run();
+ await wait(0);
+ lq.run();
+ await wait(0);
+ lq.run();
+
+ // Wait for the same delay the server has
+ await wait(500);
+ // Data should only be returned once
+ await tracer.expect('data', 6);
+ });
+
+ it(`cancels requests when server pushes`, async () => {
+ mockBasicServer();
+ tracer.start();
+
+ const query = q('transactions').select('*');
+
+ liveQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
+
+ // Simulate a sync event
+ // Send a push in the middle of the query running for the first run
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+
+ // The first request should get handled, but there should be no
+ // `data` event
+ await tracer.expect('server-query');
+
+ // The live query simply reruns the query, ignoring the first result
+ await tracer.expect('server-query');
+
+ // And we have data!
+ await tracer.expect('data', ['*']);
+ });
+
+ it(`reruns if data changes in the middle of *any* request`, async () => {
+ mockBasicServer(500);
+ tracer.start();
+
+ const query = q('transactions').select('*');
+
+ liveQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
+
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+
+ // Simulate a sync event
+ // Send two pushes in a row
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+
+ // Two requests will be made to the server, but the first one
+ // should be ignored and we only get one data back
+ await tracer.expect('server-query');
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ });
+
+ it(`unsubscribes correctly`, () => async done => {
+ mockBasicServer();
+ tracer.start();
+
+ const query = q('transactions').select('*');
+
+ const lq = liveQuery(query, {
+ onData: data => tracer.event('data', data),
+ });
+
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ lq.unsubscribe();
+
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+
+ // Wait a bit and make sure nothing comes through
+ const p = Promise.race([tracer.expect('server-query'), wait(100)]);
+
+ await expect(p).resolves.toEqual('wait(100)');
+ done();
+ });
+});
diff --git a/packages/desktop-client/src/queries/liveQuery.ts b/packages/desktop-client/src/queries/liveQuery.ts
new file mode 100644
index 0000000000..2e4e46cd05
--- /dev/null
+++ b/packages/desktop-client/src/queries/liveQuery.ts
@@ -0,0 +1,217 @@
+// @ts-strict-ignore
+import { listen } from 'loot-core/platform/client/fetch';
+import { type Query } from 'loot-core/shared/query';
+
+import { aqlQuery } from './aqlQuery';
+
+export function liveQuery<TResponse = unknown>(
+ query: Query,
+ {
+ onData,
+ onError,
+ options = {},
+ }: {
+ onData?: Listener<TResponse>;
+ onError?: (error: Error) => void;
+ options?: LiveQueryOptions;
+ },
+): LiveQuery<TResponse> {
+ return LiveQuery.runLiveQuery<TResponse>(query, onData, onError, options);
+}
+
+type Data<TResponse> = TResponse[];
+
+type Listener<TResponse = unknown> = (
+ data: Data<TResponse>,
+ previousData: Data<TResponse>,
+) => void;
+
+export type LiveQueryOptions = {
+ onlySync?: boolean;
+};
+
+// Subscribe and refetch
+export class LiveQuery<TResponse = unknown> {
+ private _unsubscribeSyncEvent: () => void | null;
+ private _data: Data<TResponse>;
+ private _dependencies: Set<string>;
+ private _listeners: Array<Listener<TResponse>>;
+ private _supportedSyncTypes: Set<'applied' | 'success'>;
+ private _query: Query;
+ private _onError: (error: Error) => void;
+
+ get query() {
+ return this._query;
+ }
+
+ get data() {
+ return this._data;
+ }
+
+ private set data(data: Data<TResponse>) {
+ this._data = data;
+ }
+
+ get isRunning() {
+ return this._unsubscribeSyncEvent != null;
+ }
+
+ // Async coordination
+ private _inflightRequestId: number | null;
+
+ protected get inflightRequestId() {
+ return this._inflightRequestId;
+ }
+
+ private set inflightRequestId(id: number) {
+ this._inflightRequestId = id;
+ }
+
+ constructor(
+ query: Query,
+ onData: Listener<TResponse>,
+ onError?: (error: Error) => void,
+ options: LiveQueryOptions = {},
+ ) {
+ this._query = query;
+ this._data = null;
+ this._dependencies = null;
+ this._listeners = [];
+ this._onError = onError || (() => {});
+
+ // TODO: error types?
+ this._supportedSyncTypes = options.onlySync
+ ? new Set(['success'])
+ : new Set(['applied', 'success']);
+
+ if (onData) {
+ this.addListener(onData);
+ }
+ }
+
+ addListener = (func: Listener<TResponse>) => {
+ this._listeners.push(func);
+
+ return () => {
+ this._listeners = this._listeners.filter(l => l !== func);
+ };
+ };
+
+ protected onData = (data: Data<TResponse>, prevData: Data<TResponse>) => {
+ for (let i = 0; i < this._listeners.length; i++) {
+ this._listeners[i](data, prevData);
+ }
+ };
+
+ protected onError = (error: Error) => {
+ this._onError(error);
+ };
+
+ protected onUpdate = (tables: string[]) => {
+ // We might not know the dependencies if the first query result
+ // hasn't come back yet
+ if (
+ this._dependencies == null ||
+ tables.find(table => this._dependencies.has(table))
+ ) {
+ this.run();
+ }
+ };
+
+ run = () => {
+ this.subscribe();
+ return this.fetchData(() => aqlQuery(this._query));
+ };
+
+ static runLiveQuery = <TResponse>(
+ query: Query,
+ onData: Listener<TResponse>,
+ onError: (error: Error) => void,
+ options: LiveQueryOptions = {},
+ ) => {
+ const liveQuery = new LiveQuery<TResponse>(query, onData, onError, options);
+ liveQuery.run();
+ return liveQuery;
+ };
+
+ protected subscribe = () => {
+ if (this._unsubscribeSyncEvent == null) {
+ this._unsubscribeSyncEvent = listen('sync-event', event => {
+ // If the user is doing optimistic updates, they don't want to
+ // always refetch whenever something changes because it would
+ // refetch all data after they've already updated the UI. This
+ // voids the perf benefits of optimistic updates. Allow querys
+ // to only react to remote syncs. By default, queries will
+ // always update to all changes.
+ if (
+ (event.type === 'applied' || event.type === 'success') &&
+ this._supportedSyncTypes.has(event.type)
+ ) {
+ this.onUpdate(event.tables);
+ }
+ });
+ }
+ };
+
+ unsubscribe = () => {
+ if (this._unsubscribeSyncEvent) {
+ this._unsubscribeSyncEvent();
+ this._unsubscribeSyncEvent = null;
+ }
+ };
+
+ protected _optimisticUpdate = (
+ updateFn: (data: Data<TResponse>) => Data<TResponse>,
+ ) => {
+ const previousData = this.data;
+ this.updateData(updateFn);
+ this.onData(this.data, previousData);
+ };
+
+ optimisticUpdate = (dataFunc: (data: Data<TResponse>) => Data<TResponse>) => {
+ this._optimisticUpdate(dataFunc);
+ };
+
+ protected updateData = (
+ updateFn: (data: Data<TResponse>) => Data<TResponse>,
+ ) => {
+ this.data = updateFn(this.data);
+ };
+
+ protected fetchData = async (
+ runQuery: () => Promise<{
+ data: Data<TResponse>;
+ dependencies: string[];
+ }>,
+ ) => {
+ // TODO: precompile queries, or cache compilation results on the
+ // backend. could give a query an id which makes it cacheable via
+ // an LRU cache
+
+ const reqId = Math.random();
+ this.inflightRequestId = reqId;
+
+ try {
+ const { data, dependencies } = await runQuery();
+
+ // Regardless if this request was cancelled or not, save the
+ // dependencies. The query can't change so all requests will
+ // return the same deps.
+ if (this._dependencies == null) {
+ this._dependencies = new Set(dependencies);
+ }
+
+ // Only fire events if this hasn't been cancelled and if we're
+ // still subscribed (`this.unsubscribeSyncEvent` will exist)
+ if (this.inflightRequestId === reqId && this._unsubscribeSyncEvent) {
+ const previousData = this.data;
+ this.data = data;
+ this.onData(this.data, previousData);
+ this.inflightRequestId = null;
+ }
+ } catch (e) {
+ console.log('Error fetching data', e);
+ this.onError(e);
+ }
+ };
+}
diff --git a/packages/loot-core/src/client/query-helpers.test.ts b/packages/desktop-client/src/queries/pagedQuery.test.ts
similarity index 54%
rename from packages/loot-core/src/client/query-helpers.test.ts
rename to packages/desktop-client/src/queries/pagedQuery.test.ts
index fb466a1d34..b14f3acf14 100644
--- a/packages/loot-core/src/client/query-helpers.test.ts
+++ b/packages/desktop-client/src/queries/pagedQuery.test.ts
@@ -1,10 +1,10 @@
// @ts-strict-ignore
-import { initServer, serverPush } from '../platform/client/fetch';
-import { subDays } from '../shared/months';
-import { q } from '../shared/query';
-import { tracer } from '../shared/test-helpers';
+import * as fetch from 'loot-core/platform/client/fetch';
+import { subDays } from 'loot-core/shared/months';
+import { q } from 'loot-core/shared/query';
+import { resetTracer, tracer } from 'loot-core/shared/test-helpers';
-import { aqlQuery, liveQuery, pagedQuery } from './query-helpers';
+import { pagedQuery } from './pagedQuery';
function wait(n) {
return new Promise(resolve => setTimeout(() => resolve(`wait(${n})`), n));
@@ -78,9 +78,40 @@ function runPagedQuery(query, data) {
throw new Error('Unable to execute query: ' + JSON.stringify(query, null, 2));
}
-function initBasicServer(delay?) {
- initServer({
- query: async query => {
+const eventListeners = new Map();
+
+function clearEventListeners() {
+ eventListeners.clear();
+}
+
+function mockListen(name, listener): () => void {
+ if (!eventListeners.get(name)) {
+ eventListeners.set(name, []);
+ }
+ eventListeners.get(name).push(listener);
+
+ return () => {
+ const arr = eventListeners.get(name);
+ eventListeners.set(
+ name,
+ arr.filter(l => l !== listener),
+ );
+ };
+}
+
+function mockPublishEvent(name, args) {
+ const listeners = eventListeners.get(name);
+ if (listeners) {
+ listeners.forEach(listener => {
+ listener(args);
+ });
+ }
+}
+
+async function mockSend(name, args, { delay }) {
+ switch (name) {
+ case 'query':
+ const query = args;
if (!isCountQuery(query)) {
tracer.event('server-query');
}
@@ -88,11 +119,32 @@ function initBasicServer(delay?) {
await wait(delay);
}
return { data: query.selectExpressions, dependencies: ['transactions'] };
+ default:
+ throw new Error(`Command not implemented: ${name}`);
+ }
+}
+
+function mockServer({ send = mockSend, listen = mockListen }) {
+ vi.spyOn(fetch, 'send').mockImplementation((name, args) => {
+ return send(name, args, { delay: 0 });
+ });
+ vi.spyOn(fetch, 'listen').mockImplementation(listen);
+}
+
+function clearMockServer() {
+ clearEventListeners();
+ vi.clearAllMocks();
+}
+
+function mockBasicServer(delay?) {
+ mockServer({
+ send: (name, args) => {
+ return mockSend(name, args, { delay });
},
});
}
-function initPagingServer(
+function mockPagingServer(
dataLength,
{ delay, eventType = 'select' }: { delay?: number; eventType?: string } = {},
) {
@@ -101,202 +153,232 @@ function initPagingServer(
data.push({ id: i, date: subDays('2020-05-01', Math.floor(i / 5)) });
}
- initServer({
- query: async query => {
- tracer.event(
- 'server-query',
- eventType === 'select' ? query.selectExpressions : query,
- );
- if (delay) {
- await wait(delay);
+ mockServer({
+ send: async (name, args) => {
+ switch (name) {
+ case 'query':
+ const query = args;
+ tracer.event(
+ 'server-query',
+ eventType === 'select' ? query.selectExpressions : query,
+ );
+ if (delay) {
+ await wait(delay);
+ }
+ return {
+ data: runPagedQuery(query, data),
+ dependencies: ['transactions'],
+ };
+ default:
+ throw new Error(`Command not implemented: ${name}`);
}
- return {
- data: runPagedQuery(query, data),
- dependencies: ['transactions'],
- };
},
});
return data;
}
-describe('query helpers', () => {
- it('aqlQuery runs a query', async () => {
- initServer({
- query: query => Promise.resolve({ data: query, dependencies: [] }),
- });
-
- const query = q('transactions').select('*');
- const { data } = await aqlQuery(query);
- expect(data).toEqual(query.serialize());
+describe('pagedQuery', () => {
+ beforeEach(() => {
+ resetTracer();
+ clearMockServer();
});
- ['liveQuery', 'pagedQuery'].forEach(queryType => {
- const doQuery = queryType === 'liveQuery' ? liveQuery : pagedQuery;
-
- it(`${queryType} runs and subscribes to a query`, async () => {
- initBasicServer();
- tracer.start();
-
- const query = q('transactions').select('*');
- doQuery(query, { onData: data => tracer.event('data', data) });
+ it(`runs and subscribes to a query`, async () => {
+ mockBasicServer();
+ tracer.start();
- await tracer.expect('server-query');
- await tracer.expect('data', ['*']);
+ const query = q('transactions').select('*');
+ pagedQuery(query, { onData: data => tracer.event('data', data) });
- serverPush('sync-event', { type: 'success', tables: ['transactions'] });
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
- await tracer.expect('server-query');
- await tracer.expect('data', ['*']);
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
});
- it(`${queryType} runs but ignores applied events (onlySync: true)`, async () => {
- initBasicServer();
- tracer.start();
-
- const query = q('transactions').select('*');
- doQuery(query, {
- onData: data => tracer.event('data', data),
- options: { onlySync: true },
- });
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ });
- await tracer.expect('server-query');
- await tracer.expect('data', ['*']);
- serverPush('sync-event', { type: 'applied', tables: ['transactions'] });
+ it(`runs but ignores applied events (onlySync: true)`, async () => {
+ mockBasicServer();
+ tracer.start();
- const p = Promise.race([tracer.wait('server-query'), wait(100)]);
- expect(await p).toEqual('wait(100)');
+ const query = q('transactions').select('*');
+ pagedQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
});
- it(`${queryType} runs and updates with sync events (onlySync: true)`, async () => {
- initBasicServer();
- tracer.start();
-
- const query = q('transactions').select('*');
- doQuery(query, {
- onData: data => tracer.event('data', data),
- options: { onlySync: true },
- });
-
- await tracer.expect('server-query');
- await tracer.expect('data', ['*']);
- serverPush('sync-event', { type: 'success', tables: ['transactions'] });
- await tracer.expect('server-query');
- await tracer.expect('data', ['*']);
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'applied',
+ tables: ['transactions'],
});
- it(`${queryType} cancels existing requests`, async () => {
- let requestId = 0;
- initServer({
- query: async query => {
- if (!isCountQuery(query)) {
- requestId++;
- }
- await wait(500);
- return { data: requestId, dependencies: ['transactions'] };
- },
- });
+ const p = Promise.race([tracer.wait('server-query'), wait(100)]);
+ expect(await p).toEqual('wait(100)');
+ });
- tracer.start();
- const query = q('transactions').select('*');
- const lq = doQuery(query, {
- onData: data => tracer.event('data', data),
- options: { onlySync: true },
- });
+ it(`runs and updates with sync events (onlySync: true)`, async () => {
+ mockBasicServer();
+ tracer.start();
- // Users should never call `run` manually but we'll do it to
- // test
+ const query = q('transactions').select('*');
+ pagedQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
- lq.run();
- await wait(0);
- lq.run();
- await wait(0);
- lq.run();
- await wait(0);
- lq.run();
- await wait(0);
- lq.run();
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ });
- // Wait for the same delay the server has
- await wait(500);
- // Data should only be returned once
- await tracer.expect('data', 6);
+ it(`cancels existing requests`, async () => {
+ let requestId = 0;
+ mockServer({
+ send: async (name, args) => {
+ switch (name) {
+ case 'query':
+ const query = args;
+ if (!isCountQuery(query)) {
+ requestId++;
+ }
+ await wait(500);
+ return { data: requestId, dependencies: ['transactions'] };
+ default:
+ throw new Error(`Command not implemented: ${name}`);
+ }
+ },
});
- it(`${queryType} cancels requests when server pushes`, async () => {
- initBasicServer();
- tracer.start();
+ tracer.start();
+ const query = q('transactions').select('*');
+ const lq = pagedQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
- const query = q('transactions').select('*');
+ // Users should never call `run` manually but we'll do it to
+ // test
+
+ lq.run();
+ await wait(0);
+ lq.run();
+ await wait(0);
+ lq.run();
+ await wait(0);
+ lq.run();
+ await wait(0);
+ lq.run();
+
+ // Wait for the same delay the server has
+ await wait(500);
+ // Data should only be returned once
+ await tracer.expect('data', 6);
+ });
- doQuery(query, {
- onData: data => tracer.event('data', data),
- options: { onlySync: true },
- });
+ it(`cancels requests when server pushes`, async () => {
+ mockBasicServer();
+ tracer.start();
- // Send a push in the middle of the query running for the first run
- serverPush('sync-event', { type: 'success', tables: ['transactions'] });
- // The first request should get handled, but there should be no
- // `data` event
- await tracer.expect('server-query');
+ const query = q('transactions').select('*');
- // The live query simply reruns the query, ignoring the first result
- await tracer.expect('server-query');
+ pagedQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
- // And we have data!
- await tracer.expect('data', ['*']);
+ // Simulate a sync event
+ // Send a push in the middle of the query running for the first run
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
});
+ // The first request should get handled, but there should be no
+ // `data` event
+ await tracer.expect('server-query');
- it(`${queryType} reruns if data changes in the middle of *any* request`, async () => {
- initBasicServer(500);
- tracer.start();
+ // The live query simply reruns the query, ignoring the first result
+ await tracer.expect('server-query');
- const query = q('transactions').select('*');
+ // And we have data!
+ await tracer.expect('data', ['*']);
+ });
- doQuery(query, {
- onData: data => tracer.event('data', data),
- options: { onlySync: true },
- });
+ it(`reruns if data changes in the middle of *any* request`, async () => {
+ mockBasicServer(500);
+ tracer.start();
- await tracer.expect('server-query');
- await tracer.expect('data', ['*']);
+ const query = q('transactions').select('*');
+
+ pagedQuery(query, {
+ onData: data => tracer.event('data', data),
+ options: { onlySync: true },
+ });
- // Send two pushes in a row
- serverPush('sync-event', { type: 'success', tables: ['transactions'] });
- serverPush('sync-event', { type: 'success', tables: ['transactions'] });
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
- // Two requests will be made to the server, but the first one
- // should be ignored and we only get one data back
- await tracer.expect('server-query');
- await tracer.expect('server-query');
- await tracer.expect('data', ['*']);
+ // Simulate a sync event
+ // Send two pushes in a row
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
});
- it(`${queryType} unsubscribes correctly`, () => async done => {
- initBasicServer();
- tracer.start();
+ // Two requests will be made to the server, but the first one
+ // should be ignored and we only get one data back
+ await tracer.expect('server-query');
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ });
- const query = q('transactions').select('*');
+ it(`unsubscribes correctly`, () => async done => {
+ mockBasicServer();
+ tracer.start();
- const lq = doQuery(query, {
- onData: data => tracer.event('data', data),
- });
+ const query = q('transactions').select('*');
- await tracer.expect('server-query');
- await tracer.expect('data', ['*']);
- lq.unsubscribe();
+ const lq = pagedQuery(query, {
+ onData: data => tracer.event('data', data),
+ });
- serverPush('sync-event', { type: 'success', tables: ['transactions'] });
+ await tracer.expect('server-query');
+ await tracer.expect('data', ['*']);
+ lq.unsubscribe();
- // Wait a bit and make sure nothing comes through
- const p = Promise.race([tracer.expect('server-query'), wait(100)]);
- expect(await p).toEqual('wait(100)');
- done();
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
});
+
+ // Wait a bit and make sure nothing comes through
+ const p = Promise.race([tracer.expect('server-query'), wait(100)]);
+ await expect(p).resolves.toEqual('wait(100)');
+ done();
});
it('pagedQuery makes requests in pages', () => async done => {
- const data = initPagingServer(1502);
+ const data = mockPagingServer(1502);
tracer.start();
const query = q('transactions').select('id');
@@ -358,7 +440,7 @@ describe('query helpers', () => {
});
it('pagedQuery allows customizing page count', async () => {
- const data = initPagingServer(50);
+ const data = mockPagingServer(50);
tracer.start();
const query = q('transactions').select('id');
@@ -375,7 +457,7 @@ describe('query helpers', () => {
});
it('pagedQuery only runs `fetchNext` once at a time', () => async done => {
- initPagingServer(1000, { delay: 200 });
+ mockPagingServer(1000, { delay: 200 });
tracer.start();
const query = q('transactions').select('id');
@@ -402,7 +484,7 @@ describe('query helpers', () => {
});
it('pagedQuery refetches all paged data on update', async () => {
- const data = initPagingServer(500, { delay: 200 });
+ const data = mockPagingServer(500, { delay: 200 });
tracer.start();
const query = q('transactions').select('id');
@@ -429,7 +511,11 @@ describe('query helpers', () => {
expect(d.length).toBe(40);
});
- serverPush('sync-event', { type: 'success', tables: ['transactions'] });
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
await tracer.expect('server-query', [{ result: { $count: '*' } }]);
await tracer.expect('server-query', ['id']);
@@ -440,7 +526,7 @@ describe('query helpers', () => {
});
it('pagedQuery reruns `fetchNext` if data changed underneath it', async () => {
- const data = initPagingServer(500, { delay: 10 });
+ const data = mockPagingServer(500, { delay: 10 });
const query = q('transactions').select('id');
const paged = pagedQuery(query, {
onData: data => tracer.event('data', data),
@@ -457,7 +543,11 @@ describe('query helpers', () => {
});
await wait(1);
- serverPush('sync-event', { type: 'success', tables: ['transactions'] });
+ // Simulate a sync event
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
// This is from the paged request, but it ignores the new data
await tracer.expect('server-query', ['id']);
@@ -484,7 +574,7 @@ describe('query helpers', () => {
});
it('pagedQuery fetches up to a specific row', async () => {
- const data = initPagingServer(500, { delay: 10, eventType: 'all' });
+ const data = mockPagingServer(500, { delay: 10, eventType: 'all' });
const query = q('transactions').select(['id', 'date']);
const paged = pagedQuery(query, {
onData: data => tracer.event('data', data),
diff --git a/packages/desktop-client/src/queries/pagedQuery.ts b/packages/desktop-client/src/queries/pagedQuery.ts
new file mode 100644
index 0000000000..24a8180074
--- /dev/null
+++ b/packages/desktop-client/src/queries/pagedQuery.ts
@@ -0,0 +1,223 @@
+// @ts-strict-ignore
+import { once } from 'loot-core/shared/async';
+import { getPrimaryOrderBy, type Query } from 'loot-core/shared/query';
+
+import { aqlQuery } from './aqlQuery';
+import { LiveQuery, type LiveQueryOptions } from './liveQuery';
+
+export function pagedQuery<TResponse = unknown>(
+ query: Query,
+ {
+ onData,
+ onError,
+ onPageData,
+ options = {},
+ }: {
+ onData?: Listener<TResponse>;
+ onError?: (error: Error) => void;
+ onPageData?: (data: Data<TResponse>) => void;
+ options?: PagedQueryOptions;
+ },
+): PagedQuery<TResponse> {
+ return PagedQuery.runPagedQuery<TResponse>(
+ query,
+ onData,
+ onError,
+ onPageData,
+ options,
+ );
+}
+
+type Data<TResponse> = TResponse[];
+
+type Listener<TResponse = unknown> = (
+ data: Data<TResponse>,
+ previousData: Data<TResponse>,
+) => void;
+
+type PagedQueryOptions = LiveQueryOptions & {
+ pageCount?: number;
+};
+
+// Paging
+export class PagedQuery<TResponse = unknown> extends LiveQuery<TResponse> {
+ private _hasReachedEnd: boolean;
+ private _onPageData: (data: Data<TResponse>) => void;
+ private _pageCount: number;
+ private _fetchDataPromise: Promise<void> | null;
+ private _totalCount: number;
+
+ get hasNext() {
+ return !this._hasReachedEnd;
+ }
+
+ get totalCount() {
+ return this._totalCount;
+ }
+
+ constructor(
+ query: Query,
+ onData: Listener<TResponse>,
+ onError?: (error: Error) => void,
+ onPageData?: (data: Data<TResponse>) => void,
+ options: PagedQueryOptions = {},
+ ) {
+ super(query, onData, onError, options);
+ this._totalCount = 0;
+ this._pageCount = options.pageCount || 500;
+ this._fetchDataPromise = null;
+ this._hasReachedEnd = false;
+ this._onPageData = onPageData || (() => {});
+ }
+
+ private fetchCount = () => {
+ return aqlQuery(this.query.calculate({ $count: '*' })).then(({ data }) => {
+ this._totalCount = data;
+ });
+ };
+
+ run = () => {
+ this.subscribe();
+
+ this._fetchDataPromise = this.fetchData(async () => {
+ this._hasReachedEnd = false;
+
+ // Also fetch the total count
+ this.fetchCount();
+
+ // If data is null, we haven't fetched anything yet so just
+ // fetch the first page
+ return aqlQuery(
+ this.query.limit(
+ this.data == null
+ ? this._pageCount
+ : Math.max(this.data.length, this._pageCount),
+ ),
+ );
+ });
+
+ return this._fetchDataPromise;
+ };
+
+ static runPagedQuery = <TResponse>(
+ query: Query,
+ onData?: Listener<TResponse>,
+ onError?: (error: Error) => void,
+ onPageData?: (data: Data<TResponse>) => void,
+ options: PagedQueryOptions = {},
+ ) => {
+ const pagedQuery = new PagedQuery<TResponse>(
+ query,
+ onData,
+ onError,
+ onPageData,
+ options,
+ );
+ pagedQuery.run();
+ return pagedQuery;
+ };
+
+ refetchUpToRow = async (id, defaultOrderBy) => {
+ this._fetchDataPromise = this.fetchData(async () => {
+ this._hasReachedEnd = false;
+
+ // Also fetch the total count
+ this.fetchCount();
+
+ const orderDesc = getPrimaryOrderBy(this.query, defaultOrderBy);
+ if (orderDesc == null) {
+ throw new Error(`refetchUpToRow requires a query with orderBy`);
+ }
+
+ const { field, order } = orderDesc;
+
+ let result = await aqlQuery(this.query.filter({ id }).select(field));
+ if (result.data.length === 0) {
+ // This row is not part of this set anymore, we can't do
+ // this. We stop early to avoid possibly pulling in a ton of
+ // data that we don't need
+ return;
+ }
+ const fullRow = result.data[0];
+
+ result = await aqlQuery(
+ this.query.filter({
+ [field]: {
+ [order === 'asc' ? '$lte' : '$gte']: fullRow[field],
+ },
+ }),
+ );
+ const data = result.data;
+
+ // Load in an extra page to make room for the UI to show some
+ // data after it
+ result = await aqlQuery(
+ this.query
+ .filter({
+ [field]: {
+ [order === 'asc' ? '$gt' : '$lt']: fullRow[field],
+ },
+ })
+ .limit(this._pageCount),
+ );
+
+ return {
+ data: data.concat(result.data),
+ dependencies: result.dependencies,
+ };
+ });
+
+ return this._fetchDataPromise;
+ };
+
+ private onPageData = (data: Data<TResponse>) => {
+ this._onPageData(data);
+ };
+
+ // The public version of this function is created below and
+ // throttled by `once`
+ private _fetchNext = async () => {
+ while (this.inflightRequestId) {
+ await this._fetchDataPromise;
+ }
+
+ const previousData = this.data;
+
+ if (!this._hasReachedEnd) {
+ const { data } = await aqlQuery(
+ this.query.limit(this._pageCount).offset(previousData.length),
+ );
+
+ // If either there is an existing request in flight or the data
+ // has already changed underneath it, we can't reliably concat
+ // the data since it's different now. Need to re-run the whole
+ // process again
+ if (this.inflightRequestId || previousData !== this.data) {
+ return this._fetchNext();
+ } else {
+ if (data.length === 0) {
+ this._hasReachedEnd = true;
+ } else {
+ this._hasReachedEnd = data.length < this._pageCount;
+
+ const prevData = this.data;
+ this.updateData(currentData => currentData.concat(data));
+
+ // Handle newly loaded page data
+ this.onPageData(data);
+
+ // Handle entire data
+ this.onData(this.data, prevData);
+ }
+ }
+ }
+ };
+
+ fetchNext: () => Promise<void> = once(this._fetchNext);
+
+ optimisticUpdate = (updateFn: (data: Data<TResponse>) => Data<TResponse>) => {
+ const previousData = this.data;
+ this._optimisticUpdate(updateFn);
+ this._totalCount += this.data.length - previousData.length;
+ };
+}
diff --git a/packages/loot-core/src/client/queries.ts b/packages/desktop-client/src/queries/queries.ts
similarity index 96%
rename from packages/loot-core/src/client/queries.ts
rename to packages/desktop-client/src/queries/queries.ts
index c0c4256b54..40d3331d9e 100644
--- a/packages/loot-core/src/client/queries.ts
+++ b/packages/desktop-client/src/queries/queries.ts
@@ -1,23 +1,27 @@
// @ts-strict-ignore
import { parse as parseDate, isValid as isDateValid } from 'date-fns';
-import {
- parametrizedField,
- type SheetFields,
- type Binding,
- type SheetNames,
-} from '../../../desktop-client/src/components/spreadsheet';
import {
dayFromDate,
getDayMonthRegex,
getDayMonthFormat,
getShortYearRegex,
getShortYearFormat,
-} from '../shared/months';
-import { q, type Query } from '../shared/query';
-import { currencyToAmount, amountToInteger } from '../shared/util';
-import { type CategoryEntity, type AccountEntity } from '../types/models';
-import { type SyncedPrefs } from '../types/prefs';
+} from 'loot-core/shared/months';
+import { q, type Query } from 'loot-core/shared/query';
+import { currencyToAmount, amountToInteger } from 'loot-core/shared/util';
+import {
+ type CategoryEntity,
+ type AccountEntity,
+} from 'loot-core/types/models';
+import { type SyncedPrefs } from 'loot-core/types/prefs';
+
+import {
+ parametrizedField,
+ type SheetFields,
+ type Binding,
+ type SheetNames,
+} from '../components/spreadsheet';
type BudgetType<SheetName extends SheetNames> = Record<
string,
diff --git a/packages/desktop-client/src/style/styles.ts b/packages/desktop-client/src/style/styles.ts
index ce079661c8..6d358939db 100644
--- a/packages/desktop-client/src/style/styles.ts
+++ b/packages/desktop-client/src/style/styles.ts
@@ -1,7 +1,7 @@
// @ts-strict-ignore
import { styles } from '@actual-app/components/styles';
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
let hiddenScrollbars = false;
diff --git a/packages/loot-core/src/client/shared-listeners.ts b/packages/desktop-client/src/sync-events.ts
similarity index 93%
rename from packages/loot-core/src/client/shared-listeners.ts
rename to packages/desktop-client/src/sync-events.ts
index f9b65af7e8..5f3ff4a74e 100644
--- a/packages/loot-core/src/client/shared-listeners.ts
+++ b/packages/desktop-client/src/sync-events.ts
@@ -1,28 +1,19 @@
// @ts-strict-ignore
-// This is temporary until we move all loot-core/client over to desktop-client.
-/* eslint-disable no-restricted-imports */
-import { resetSync, sync } from '@actual-app/web/src/app/appSlice';
-import {
- closeAndDownloadBudget,
- uploadBudget,
-} from '@actual-app/web/src/budgets/budgetsSlice';
-import { pushModal } from '@actual-app/web/src/modals/modalsSlice';
+import { t } from 'i18next';
+
+import { listen, send } from 'loot-core/platform/client/fetch';
+
+import { resetSync, sync } from './app/appSlice';
+import { closeAndDownloadBudget, uploadBudget } from './budgets/budgetsSlice';
+import { pushModal } from './modals/modalsSlice';
import {
addNotification,
type Notification,
-} from '@actual-app/web/src/notifications/notificationsSlice';
-import { loadPrefs } from '@actual-app/web/src/prefs/prefsSlice';
-import {
- getAccounts,
- getCategories,
- getPayees,
-} from '@actual-app/web/src/queries/queriesSlice';
-import { type AppStore } from '@actual-app/web/src/redux/store';
-import { signOut } from '@actual-app/web/src/users/usersSlice';
-/* eslint-enable no-restricted-imports */
-import { t } from 'i18next';
-
-import { listen, send } from '../platform/client/fetch';
+} from './notifications/notificationsSlice';
+import { loadPrefs } from './prefs/prefsSlice';
+import { getAccounts, getCategories, getPayees } from './queries/queriesSlice';
+import { type AppStore } from './redux/store';
+import { signOut } from './users/usersSlice';
export function listenForSyncEvent(store: AppStore) {
// TODO: Should this run on mobile too?
diff --git a/packages/loot-core/src/client/undo.ts b/packages/desktop-client/src/undo/index.ts
similarity index 91%
rename from packages/loot-core/src/client/undo.ts
rename to packages/desktop-client/src/undo/index.ts
index d34608f16c..509f59330d 100644
--- a/packages/loot-core/src/client/undo.ts
+++ b/packages/desktop-client/src/undo/index.ts
@@ -1,4 +1,4 @@
-import { send } from '../platform/client/fetch';
+import { send } from 'loot-core/platform/client/fetch';
function throttle(callback: () => void, wait: number) {
let waiting = false;
diff --git a/packages/desktop-client/src/util/versions.ts b/packages/desktop-client/src/util/versions.ts
index d8c1033dd6..d02ef3de19 100644
--- a/packages/desktop-client/src/util/versions.ts
+++ b/packages/desktop-client/src/util/versions.ts
@@ -1,5 +1,5 @@
// @ts-strict-ignore
-import * as Platform from 'loot-core/client/platform';
+import * as Platform from 'loot-core/shared/platform';
function parseSemanticVersion(versionString): [number, number, number] {
return versionString
diff --git a/packages/loot-core/src/client/query-helpers.ts b/packages/loot-core/src/client/query-helpers.ts
deleted file mode 100644
index 28839f3df9..0000000000
--- a/packages/loot-core/src/client/query-helpers.ts
+++ /dev/null
@@ -1,430 +0,0 @@
-// @ts-strict-ignore
-import { listen, send } from '../platform/client/fetch';
-import { once } from '../shared/async';
-import { getPrimaryOrderBy, type Query } from '../shared/query';
-
-export async function aqlQuery(query: Query) {
- return send('query', query.serialize());
-}
-
-export function liveQuery<TResponse = unknown>(
- query: Query,
- {
- onData,
- onError,
- options = {},
- }: {
- onData?: Listener<TResponse>;
- onError?: (error: Error) => void;
- options?: LiveQueryOptions;
- },
-): LiveQuery<TResponse> {
- return LiveQuery.runLiveQuery<TResponse>(query, onData, onError, options);
-}
-
-export function pagedQuery<TResponse = unknown>(
- query: Query,
- {
- onData,
- onError,
- onPageData,
- options = {},
- }: {
- onData?: Listener<TResponse>;
- onError?: (error: Error) => void;
- onPageData?: (data: Data<TResponse>) => void;
- options?: PagedQueryOptions;
- },
-): PagedQuery<TResponse> {
- return PagedQuery.runPagedQuery<TResponse>(
- query,
- onData,
- onError,
- onPageData,
- options,
- );
-}
-
-type Data<TResponse> = TResponse[];
-
-type Listener<TResponse = unknown> = (
- data: Data<TResponse>,
- previousData: Data<TResponse>,
-) => void;
-
-type LiveQueryOptions = {
- onlySync?: boolean;
-};
-
-// Subscribe and refetch
-export class LiveQuery<TResponse = unknown> {
- private _unsubscribeSyncEvent: () => void | null;
- private _data: Data<TResponse>;
- private _dependencies: Set<string>;
- private _listeners: Array<Listener<TResponse>>;
- private _supportedSyncTypes: Set<'applied' | 'success'>;
- private _query: Query;
- private _onError: (error: Error) => void;
-
- get query() {
- return this._query;
- }
-
- get data() {
- return this._data;
- }
-
- private set data(data: Data<TResponse>) {
- this._data = data;
- }
-
- get isRunning() {
- return this._unsubscribeSyncEvent != null;
- }
-
- // Async coordination
- private _inflightRequestId: number | null;
-
- protected get inflightRequestId() {
- return this._inflightRequestId;
- }
-
- private set inflightRequestId(id: number) {
- this._inflightRequestId = id;
- }
-
- constructor(
- query: Query,
- onData: Listener<TResponse>,
- onError?: (error: Error) => void,
- options: LiveQueryOptions = {},
- ) {
- this._query = query;
- this._data = null;
- this._dependencies = null;
- this._listeners = [];
- this._onError = onError || (() => {});
-
- // TODO: error types?
- this._supportedSyncTypes = options.onlySync
- ? new Set(['success'])
- : new Set(['applied', 'success']);
-
- if (onData) {
- this.addListener(onData);
- }
- }
-
- addListener = (func: Listener<TResponse>) => {
- this._listeners.push(func);
-
- return () => {
- this._listeners = this._listeners.filter(l => l !== func);
- };
- };
-
- protected onData = (data: Data<TResponse>, prevData: Data<TResponse>) => {
- for (let i = 0; i < this._listeners.length; i++) {
- this._listeners[i](data, prevData);
- }
- };
-
- protected onError = (error: Error) => {
- this._onError(error);
- };
-
- protected onUpdate = (tables: string[]) => {
- // We might not know the dependencies if the first query result
- // hasn't come back yet
- if (
- this._dependencies == null ||
- tables.find(table => this._dependencies.has(table))
- ) {
- this.run();
- }
- };
-
- run = () => {
- this.subscribe();
- return this.fetchData(() => aqlQuery(this._query));
- };
-
- static runLiveQuery = <TResponse>(
- query: Query,
- onData: Listener<TResponse>,
- onError: (error: Error) => void,
- options: LiveQueryOptions = {},
- ) => {
- const liveQuery = new LiveQuery<TResponse>(query, onData, onError, options);
- liveQuery.run();
- return liveQuery;
- };
-
- protected subscribe = () => {
- if (this._unsubscribeSyncEvent == null) {
- this._unsubscribeSyncEvent = listen('sync-event', event => {
- // If the user is doing optimistic updates, they don't want to
- // always refetch whenever something changes because it would
- // refetch all data after they've already updated the UI. This
- // voids the perf benefits of optimistic updates. Allow querys
- // to only react to remote syncs. By default, queries will
- // always update to all changes.
- if (
- (event.type === 'applied' || event.type === 'success') &&
- this._supportedSyncTypes.has(event.type)
- ) {
- this.onUpdate(event.tables);
- }
- });
- }
- };
-
- unsubscribe = () => {
- if (this._unsubscribeSyncEvent) {
- this._unsubscribeSyncEvent();
- this._unsubscribeSyncEvent = null;
- }
- };
-
- protected _optimisticUpdate = (
- updateFn: (data: Data<TResponse>) => Data<TResponse>,
- ) => {
- const previousData = this.data;
- this.updateData(updateFn);
- this.onData(this.data, previousData);
- };
-
- optimisticUpdate = (dataFunc: (data: Data<TResponse>) => Data<TResponse>) => {
- this._optimisticUpdate(dataFunc);
- };
-
- protected updateData = (
- updateFn: (data: Data<TResponse>) => Data<TResponse>,
- ) => {
- this.data = updateFn(this.data);
- };
-
- protected fetchData = async (
- aqlQuery: () => Promise<{
- data: Data<TResponse>;
- dependencies: string[];
- }>,
- ) => {
- // TODO: precompile queries, or cache compilation results on the
- // backend. could give a query an id which makes it cacheable via
- // an LRU cache
-
- const reqId = Math.random();
- this.inflightRequestId = reqId;
-
- try {
- const { data, dependencies } = await aqlQuery();
-
- // Regardless if this request was cancelled or not, save the
- // dependencies. The query can't change so all requests will
- // return the same deps.
- if (this._dependencies == null) {
- this._dependencies = new Set(dependencies);
- }
-
- // Only fire events if this hasn't been cancelled and if we're
- // still subscribed (`this.unsubscribeSyncEvent` will exist)
- if (this.inflightRequestId === reqId && this._unsubscribeSyncEvent) {
- const previousData = this.data;
- this.data = data;
- this.onData(this.data, previousData);
- this.inflightRequestId = null;
- }
- } catch (e) {
- console.log('Error fetching data', e);
- this.onError(e);
- }
- };
-}
-
-type PagedQueryOptions = LiveQueryOptions & {
- pageCount?: number;
-};
-
-// Paging
-export class PagedQuery<TResponse = unknown> extends LiveQuery<TResponse> {
- private _hasReachedEnd: boolean;
- private _onPageData: (data: Data<TResponse>) => void;
- private _pageCount: number;
- private _fetchDataPromise: Promise<void> | null;
- private _totalCount: number;
-
- get hasNext() {
- return !this._hasReachedEnd;
- }
-
- get totalCount() {
- return this._totalCount;
- }
-
- constructor(
- query: Query,
- onData: Listener<TResponse>,
- onError?: (error: Error) => void,
- onPageData?: (data: Data<TResponse>) => void,
- options: PagedQueryOptions = {},
- ) {
- super(query, onData, onError, options);
- this._totalCount = 0;
- this._pageCount = options.pageCount || 500;
- this._fetchDataPromise = null;
- this._hasReachedEnd = false;
- this._onPageData = onPageData || (() => {});
- }
-
- private fetchCount = () => {
- return aqlQuery(this.query.calculate({ $count: '*' })).then(({ data }) => {
- this._totalCount = data;
- });
- };
-
- run = () => {
- this.subscribe();
-
- this._fetchDataPromise = this.fetchData(async () => {
- this._hasReachedEnd = false;
-
- // Also fetch the total count
- this.fetchCount();
-
- // If data is null, we haven't fetched anything yet so just
- // fetch the first page
- return aqlQuery(
- this.query.limit(
- this.data == null
- ? this._pageCount
- : Math.max(this.data.length, this._pageCount),
- ),
- );
- });
-
- return this._fetchDataPromise;
- };
-
- static runPagedQuery = <TResponse>(
- query: Query,
- onData?: Listener<TResponse>,
- onError?: (error: Error) => void,
- onPageData?: (data: Data<TResponse>) => void,
- options: PagedQueryOptions = {},
- ) => {
- const pagedQuery = new PagedQuery<TResponse>(
- query,
- onData,
- onError,
- onPageData,
- options,
- );
- pagedQuery.run();
- return pagedQuery;
- };
-
- refetchUpToRow = async (id, defaultOrderBy) => {
- this._fetchDataPromise = this.fetchData(async () => {
- this._hasReachedEnd = false;
-
- // Also fetch the total count
- this.fetchCount();
-
- const orderDesc = getPrimaryOrderBy(this.query, defaultOrderBy);
- if (orderDesc == null) {
- throw new Error(`refetchUpToRow requires a query with orderBy`);
- }
-
- const { field, order } = orderDesc;
-
- let result = await aqlQuery(this.query.filter({ id }).select(field));
- if (result.data.length === 0) {
- // This row is not part of this set anymore, we can't do
- // this. We stop early to avoid possibly pulling in a ton of
- // data that we don't need
- return;
- }
- const fullRow = result.data[0];
-
- result = await aqlQuery(
- this.query.filter({
- [field]: {
- [order === 'asc' ? '$lte' : '$gte']: fullRow[field],
- },
- }),
- );
- const data = result.data;
-
- // Load in an extra page to make room for the UI to show some
- // data after it
- result = await aqlQuery(
- this.query
- .filter({
- [field]: {
- [order === 'asc' ? '$gt' : '$lt']: fullRow[field],
- },
- })
- .limit(this._pageCount),
- );
-
- return {
- data: data.concat(result.data),
- dependencies: result.dependencies,
- };
- });
-
- return this._fetchDataPromise;
- };
-
- private onPageData = (data: Data<TResponse>) => {
- this._onPageData(data);
- };
-
- // The public version of this function is created below and
- // throttled by `once`
- private _fetchNext = async () => {
- while (this.inflightRequestId) {
- await this._fetchDataPromise;
- }
-
- const previousData = this.data;
-
- if (!this._hasReachedEnd) {
- const { data } = await aqlQuery(
- this.query.limit(this._pageCount).offset(previousData.length),
- );
-
- // If either there is an existing request in flight or the data
- // has already changed underneath it, we can't reliably concat
- // the data since it's different now. Need to re-run the whole
- // process again
- if (this.inflightRequestId || previousData !== this.data) {
- return this._fetchNext();
- } else {
- if (data.length === 0) {
- this._hasReachedEnd = true;
- } else {
- this._hasReachedEnd = data.length < this._pageCount;
-
- const prevData = this.data;
- this.updateData(currentData => currentData.concat(data));
-
- // Handle newly loaded page data
- this.onPageData(data);
-
- // Handle entire data
- this.onData(this.data, prevData);
- }
- }
- }
- };
-
- fetchNext: () => Promise<void> = once(this._fetchNext);
-
- optimisticUpdate = (updateFn: (data: Data<TResponse>) => Data<TResponse>) => {
- const previousData = this.data;
- this._optimisticUpdate(updateFn);
- this._totalCount += this.data.length - previousData.length;
- };
-}
diff --git a/packages/loot-core/src/client/reports.ts b/packages/loot-core/src/client/reports.ts
deleted file mode 100644
index 8b34fc93d4..0000000000
--- a/packages/loot-core/src/client/reports.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import {
- type AccountEntity,
- type CategoryEntity,
- type RuleConditionEntity,
- type PayeeEntity,
-} from '../types/models';
-
-/**
- * Checks if the given conditions have issues
- * (i.e. non-existing category/payee/account being used).
- */
-export function calculateHasWarning(
- conditions: RuleConditionEntity[],
- {
- categories,
- accounts,
- payees,
- }: {
- categories: CategoryEntity[];
- accounts: AccountEntity[];
- payees: PayeeEntity[];
- },
-) {
- const categoryIds = new Set(categories.map(({ id }) => id));
- const payeeIds = new Set(payees.map(({ id }) => id));
- const accountIds = new Set(accounts.map(({ id }) => id));
-
- if (!conditions) {
- return false;
- }
-
- for (const cond of conditions) {
- const { field, value, op } = cond;
- const isMultiCondition = Array.isArray(value);
- const isSupportedSingleCondition = ['is', 'isNot'].includes(op);
-
- // Regex and other more complicated operations are not supported
- if (!isSupportedSingleCondition && !isMultiCondition) {
- continue;
- }
-
- // Empty value.. we can skip
- if (!isMultiCondition && !value) {
- continue;
- }
-
- switch (field) {
- case 'account':
- if (isMultiCondition) {
- if (value.find(val => !accountIds.has(val))) {
- return true;
- }
- break;
- }
-
- if (!accountIds.has(value)) {
- return true;
- }
- break;
- case 'payee':
- if (isMultiCondition) {
- if (value.find(val => !payeeIds.has(val))) {
- return true;
- }
- break;
- }
-
- if (!payeeIds.has(value)) {
- return true;
- }
- break;
- case 'category':
- if (isMultiCondition) {
- if (value.find(val => !categoryIds.has(val))) {
- return true;
- }
- break;
- }
-
- if (!categoryIds.has(value)) {
- return true;
- }
- break;
- }
- }
- return false;
-}
diff --git a/packages/loot-core/src/mocks/random.ts b/packages/loot-core/src/mocks/random.ts
index 911ddf53ff..8c29fc7161 100644
--- a/packages/loot-core/src/mocks/random.ts
+++ b/packages/loot-core/src/mocks/random.ts
@@ -1,4 +1,4 @@
-import * as Platform from '../client/platform';
+import * as Platform from '../shared/platform';
// Fake "random" function used to have stable data structures for
// e2e and visual regression tests
diff --git a/packages/loot-core/src/server/budgetfiles/app.ts b/packages/loot-core/src/server/budgetfiles/app.ts
index 6d726bffd0..60fd0011f4 100644
--- a/packages/loot-core/src/server/budgetfiles/app.ts
+++ b/packages/loot-core/src/server/budgetfiles/app.ts
@@ -7,6 +7,7 @@ import * as asyncStorage from '../../platform/server/asyncStorage';
import * as connection from '../../platform/server/connection';
import * as fs from '../../platform/server/fs';
import { logger } from '../../platform/server/log';
+import * as Platform from '../../shared/platform';
import { Budget } from '../../types/budget';
import { createApp } from '../app';
import * as budget from '../budget/base';
@@ -16,7 +17,6 @@ import * as mappings from '../db/mappings';
import { handleBudgetImport, ImportableBudgetType } from '../importers';
import { app as mainApp } from '../main-app';
import { mutator } from '../mutators';
-import * as Platform from '../platform';
import * as prefs from '../prefs';
import { getServer } from '../server-config';
import * as sheet from '../sheet';
@@ -578,11 +578,7 @@ async function _loadBudget(id: Budget['id']): Promise<{
await prefs.savePrefs({ resetClock: false });
}
- if (
- !Platform.isWeb &&
- !Platform.isMobile &&
- process.env.NODE_ENV !== 'test'
- ) {
+ if (!Platform.isBrowser && process.env.NODE_ENV !== 'test') {
await startBackupService(id);
}
@@ -624,10 +620,7 @@ async function _loadBudget(id: Budget['id']): Promise<{
await asyncStorage.setItem('lastBudget', id);
- // Only upload periodically on desktop
- if (!Platform.isMobile) {
- await cloudStorage.possiblyUpload();
- }
+ await cloudStorage.possiblyUpload();
}
}
@@ -643,7 +636,7 @@ async function uploadFileWeb({
filename: string;
contents: ArrayBuffer;
}) {
- if (!Platform.isWeb) {
+ if (!Platform.isBrowser) {
return null;
}
diff --git a/packages/loot-core/src/server/main.ts b/packages/loot-core/src/server/main.ts
index f3160724d3..245e1640b1 100644
--- a/packages/loot-core/src/server/main.ts
+++ b/packages/loot-core/src/server/main.ts
@@ -26,7 +26,6 @@ import { app } from './main-app';
import { mutator, runHandler } from './mutators';
import { app as notesApp } from './notes/app';
import { app as payeesApp } from './payees/app';
-import * as Platform from './platform';
import { get } from './post';
import { app as preferencesApp } from './preferences/app';
import * as prefs from './prefs';
@@ -151,13 +150,6 @@ app.combine(
);
export function getDefaultDocumentDir() {
- if (Platform.isMobile) {
- // On mobile, unfortunately we need to be backwards compatible
- // with the old folder structure which does not store files inside
- // of an `Actual` directory. In the future, if we really care, we
- // can migrate them, but for now just return the documents dir
- return process.env.ACTUAL_DOCUMENT_DIR;
- }
return fs.join(process.env.ACTUAL_DOCUMENT_DIR, 'Actual');
}
diff --git a/packages/loot-core/src/server/platform.ts b/packages/loot-core/src/server/platform.ts
deleted file mode 100644
index 0c67da480a..0000000000
--- a/packages/loot-core/src/server/platform.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export const isMobile = false;
-export const isWeb = false;
-export const isDesktop = true;
diff --git a/packages/loot-core/src/server/platform.web.ts b/packages/loot-core/src/server/platform.web.ts
deleted file mode 100644
index c502596036..0000000000
--- a/packages/loot-core/src/server/platform.web.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export const isMobile = false;
-export const isWeb = true;
-export const isDesktop = false;
diff --git a/packages/loot-core/src/server/post.ts b/packages/loot-core/src/server/post.ts
index 90533596be..5e1a278e56 100644
--- a/packages/loot-core/src/server/post.ts
+++ b/packages/loot-core/src/server/post.ts
@@ -1,8 +1,8 @@
// @ts-strict-ignore
import { fetch } from '../platform/server/fetch';
+import * as Platform from '../shared/platform';
import { PostError } from './errors';
-import * as Platform from './platform';
function throwIfNot200(res: Response, text: string) {
if (res.status !== 200) {
@@ -190,7 +190,7 @@ export async function postBinary(url, data, headers) {
try {
res = await fetch(url, {
method: 'POST',
- body: Platform.isWeb ? data : Buffer.from(data),
+ body: Platform.isBrowser ? data : Buffer.from(data),
headers: {
'Content-Length': data.length,
'Content-Type': 'application/actual-sync',
diff --git a/packages/loot-core/src/server/sheet.ts b/packages/loot-core/src/server/sheet.ts
index d4c98c67e9..cc62892ef0 100644
--- a/packages/loot-core/src/server/sheet.ts
+++ b/packages/loot-core/src/server/sheet.ts
@@ -4,6 +4,7 @@ import { type Database } from '@jlongster/sql.js';
import { captureBreadcrumb } from '../platform/exceptions';
import * as sqlite from '../platform/server/sqlite';
import { sheetForMonth } from '../shared/months';
+import * as Platform from '../shared/platform';
import {
DbPreference,
@@ -11,7 +12,6 @@ import {
DbZeroBudget,
DbZeroBudgetMonth,
} from './db';
-import * as Platform from './platform';
import { Spreadsheet } from './spreadsheet/spreadsheet';
import { resolveName } from './spreadsheet/util';
@@ -105,7 +105,7 @@ export async function loadSpreadsheet(
const mainDb = db.getDatabase();
let cacheDb;
- if (Platform.isDesktop && cacheEnabled) {
+ if (!Platform.isBrowser && cacheEnabled) {
// Desktop apps use a separate database for the cache. This is because it is
// much more likely to directly work with files on desktop, and this makes
// it a lot clearer what the true filesize of the main db is (and avoid
diff --git a/packages/loot-core/src/client/__mocks__/platform.web.ts b/packages/loot-core/src/shared/__mocks__/platform.web.ts
similarity index 100%
rename from packages/loot-core/src/client/__mocks__/platform.web.ts
rename to packages/loot-core/src/shared/__mocks__/platform.web.ts
diff --git a/packages/loot-core/src/shared/months.ts b/packages/loot-core/src/shared/months.ts
index 715d5768bc..c6241aafcd 100644
--- a/packages/loot-core/src/shared/months.ts
+++ b/packages/loot-core/src/shared/months.ts
@@ -2,9 +2,10 @@
import * as d from 'date-fns';
import memoizeOne from 'memoize-one';
-import * as Platform from '../client/platform';
import { type SyncedPrefs } from '../types/prefs';
+import * as Platform from './platform';
+
type DateLike = string | Date;
type Day = 0 | 1 | 2 | 3 | 4 | 5 | 6;
diff --git a/packages/loot-core/src/client/platform.electron.ts b/packages/loot-core/src/shared/platform.electron.ts
similarity index 100%
rename from packages/loot-core/src/client/platform.electron.ts
rename to packages/loot-core/src/shared/platform.electron.ts
diff --git a/packages/loot-core/src/client/platform.ts b/packages/loot-core/src/shared/platform.ts
similarity index 100%
rename from packages/loot-core/src/client/platform.ts
rename to packages/loot-core/src/shared/platform.ts
diff --git a/packages/loot-core/src/client/platform.web.ts b/packages/loot-core/src/shared/platform.web.ts
similarity index 100%
rename from packages/loot-core/src/client/platform.web.ts
rename to packages/loot-core/src/shared/platform.web.ts
diff --git a/packages/loot-core/src/client/transfer.test.ts b/packages/loot-core/src/shared/transfer.test.ts
similarity index 100%
rename from packages/loot-core/src/client/transfer.test.ts
rename to packages/loot-core/src/shared/transfer.test.ts
diff --git a/packages/loot-core/src/client/transfer.ts b/packages/loot-core/src/shared/transfer.ts
similarity index 100%
rename from packages/loot-core/src/client/transfer.ts
rename to packages/loot-core/src/shared/transfer.ts
diff --git a/upcoming-release-notes/4830.md b/upcoming-release-notes/4830.md
new file mode 100644
index 0000000000..89fabd51f8
--- /dev/null
+++ b/upcoming-release-notes/4830.md
@@ -0,0 +1,6 @@
+---
+category: Maintenance
+authors: [joel-jeremy]
+---
+
+[Final PR] Move remaining loot-core/client files to desktop-client feature folders