A local-first personal finance app
Retrofit dashboard hooks to use react-query (#6957)
Joel Jeremy Marquez253530e2390b
diff --git a/packages/desktop-client/src/components/modals/CopyWidgetToDashboardModal.tsx b/packages/desktop-client/src/components/modals/CopyWidgetToDashboardModal.tsxindex 91bf440dc9..9b953d3f3e 100644--- a/packages/desktop-client/src/components/modals/CopyWidgetToDashboardModal.tsx+++ b/packages/desktop-client/src/components/modals/CopyWidgetToDashboardModal.tsx@@ -11,7 +11,7 @@ import {ModalCloseButton,ModalHeader,} from '@desktop-client/components/common/Modal';-import { useDashboardPages } from '@desktop-client/hooks/useDashboard';+import { useDashboardPages } from '@desktop-client/hooks/useDashboardPages';import type { Modal as ModalType } from '@desktop-client/modals/modalsSlice';type CopyWidgetToDashboardModalProps = Extract<@@ -23,11 +23,11 @@ export function CopyWidgetToDashboardModal({onSelect,}: CopyWidgetToDashboardModalProps) {const { t } = useTranslation();- const { data: dashboard_pages = [] } = useDashboardPages();+ const { data: dashboardPages = [] } = useDashboardPages();const items: ComponentProps<typeof Menu<string>>['items'] = useMemo(- () => dashboard_pages.map(d => ({ name: d.id, text: d.name })),- [dashboard_pages],+ () => dashboardPages.map(d => ({ name: d.id, text: d.name })),+ [dashboardPages],);return (diff --git a/packages/desktop-client/src/components/reports/DashboardHeader.tsx b/packages/desktop-client/src/components/reports/DashboardHeader.tsxindex 753f886ecc..612c4739b5 100644--- a/packages/desktop-client/src/components/reports/DashboardHeader.tsx+++ b/packages/desktop-client/src/components/reports/DashboardHeader.tsx@@ -8,28 +8,35 @@ import { Input } from '@actual-app/components/input';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';-import { send } from 'loot-core/platform/client/connection';-import type { DashboardEntity } from 'loot-core/types/models';+import type { DashboardPageEntity } from 'loot-core/types/models';++import { useRenameDashboardPageMutation } from '@desktop-client/reports/mutations';type DashboardHeaderProps = {- dashboard: DashboardEntity;+ dashboard: DashboardPageEntity;};export function DashboardHeader({ dashboard }: DashboardHeaderProps) {const { t } = useTranslation();const [editingName, setEditingName] = useState(false);+ const renameDashboardPageMutation = useRenameDashboardPageMutation();+const handleSaveName = async (newName: string) => {const trimmedName = newName.trim();if (!trimmedName || trimmedName === dashboard.name) {setEditingName(false);return;}- await send('dashboard-rename', {- id: dashboard.id,- name: trimmedName,- });- setEditingName(false);++ renameDashboardPageMutation.mutate(+ { id: dashboard.id, name: trimmedName },+ {+ onSuccess: () => {+ setEditingName(false);+ },+ },+ );};return (diff --git a/packages/desktop-client/src/components/reports/DashboardSelector.tsx b/packages/desktop-client/src/components/reports/DashboardSelector.tsxindex d98ac748a7..422816816d 100644--- a/packages/desktop-client/src/components/reports/DashboardSelector.tsx+++ b/packages/desktop-client/src/components/reports/DashboardSelector.tsx@@ -8,14 +8,14 @@ import { Menu } from '@actual-app/components/menu';import { Popover } from '@actual-app/components/popover';import { View } from '@actual-app/components/view';-import { send } from 'loot-core/platform/client/connection';-import type { DashboardEntity } from 'loot-core/types/models';+import type { DashboardPageEntity } from 'loot-core/types/models';import { useNavigate } from '@desktop-client/hooks/useNavigate';+import { useCreateDashboardPageMutation } from '@desktop-client/reports/mutations';type DashboardSelectorProps = {- dashboards: readonly DashboardEntity[];- currentDashboard: DashboardEntity;+ dashboards: readonly DashboardPageEntity[];+ currentDashboard: DashboardPageEntity;};export function DashboardSelector({@@ -27,12 +27,18 @@ export function DashboardSelector({const triggerRef = useRef(null);const [menuOpen, setMenuOpen] = useState(false);+ const createDashboardPageMutation = useCreateDashboardPageMutation();+const handleAddDashboard = async () => {const defaultName = t('New dashboard');- const newId = await send('dashboard-create', { name: defaultName });- if (newId) {- navigate(`/reports/${newId}`);- }+ createDashboardPageMutation.mutate(+ { name: defaultName },+ {+ onSuccess: id => {+ navigate(`/reports/${id}`);+ },+ },+ );};return (diff --git a/packages/desktop-client/src/components/reports/Overview.tsx b/packages/desktop-client/src/components/reports/Overview.tsxindex f864c827f3..4ad147ff13 100644--- a/packages/desktop-client/src/components/reports/Overview.tsx+++ b/packages/desktop-client/src/components/reports/Overview.tsx@@ -14,13 +14,12 @@ import { Popover } from '@actual-app/components/popover';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';-import { send } from 'loot-core/platform/client/connection';import type {CustomReportWidget,- DashboardEntity,+ DashboardPageEntity,+ DashboardWidgetEntity,ExportImportDashboard,MarkdownWidget,- Widget,} from 'loot-core/types/models';import { NON_DRAGGABLE_AREA_CLASS_NAME } from './constants';@@ -43,9 +42,9 @@ import { MOBILE_NAV_HEIGHT } from '@desktop-client/components/mobile/MobileNavTaimport { MobilePageHeader, Page } from '@desktop-client/components/Page';import { useAccounts } from '@desktop-client/hooks/useAccounts';import {- useDashboard,useDashboardPages,-} from '@desktop-client/hooks/useDashboard';+ useDashboardPageWidgets,+} from '@desktop-client/hooks/useDashboardPages';import { useFeatureFlag } from '@desktop-client/hooks/useFeatureFlag';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useReports } from '@desktop-client/hooks/useReports';@@ -57,13 +56,25 @@ import {removeNotification,} from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';--function isCustomReportWidget(widget: Widget): widget is CustomReportWidget {+import {+ useAddDashboardWidgetMutation,+ useCopyDashboardWidgetMutation,+ useDeleteDashboardPageMutation,+ useImportDashboardPageMutation,+ useRemoveDashboardWidgetMutation,+ useResetDashboardPageMutation,+ useUpdateDashboardWidgetMutation,+ useUpdateDashboardWidgetsMutation,+} from '@desktop-client/reports/mutations';++function isCustomReportWidget(+ widget: DashboardWidgetEntity,+): widget is CustomReportWidget {return widget.type === 'custom-report';}type OverviewProps = {- dashboard: DashboardEntity;+ dashboard: DashboardPageEntity;};export function Overview({ dashboard }: OverviewProps) {@@ -90,13 +101,14 @@ export function Overview({ dashboard }: OverviewProps) {() => new Map(customReports.map(report => [report.id, report])),[customReports],);- const { data: dashboard_pages = [] } = useDashboardPages();+ const { data: dashboardPages = [], isPending: isDashboardPageLoading } =+ useDashboardPages();- const { data: widgets, isLoading: isWidgetsLoading } = useDashboard(- dashboard.id,- );+ const { data: widgets = [], isPending: isWidgetsLoading } =+ useDashboardPageWidgets(dashboard.id);- const isLoading = isCustomReportsLoading || isWidgetsLoading;+ const isLoading =+ isCustomReportsLoading || isWidgetsLoading || isDashboardPageLoading;const navigate = useNavigate();@@ -202,50 +214,69 @@ export function Overview({ dashboard }: OverviewProps) {);};+ const resetDashboardPageMutation = useResetDashboardPageMutation();+const onResetDashboard = async () => {setIsImporting(true);- await send('dashboard-reset', dashboard.id);- setIsImporting(false);- onDispatchSucessNotification(- t(- "Dashboard has been successfully reset to default state. Don't like what you see? You can always press [ctrl+z](#undo) to undo.",- ),+ resetDashboardPageMutation.mutate(+ {+ id: dashboard.id,+ },+ {+ onSettled: () => {+ setIsImporting(false);+ },+ onSuccess: () => {+ onDispatchSucessNotification(+ t(+ "Dashboard has been successfully reset to default state. Don't like what you see? You can always press [ctrl+z](#undo) to undo.",+ ),+ );+ },+ },);};+ const updateDashboardWidgetsMutation = useUpdateDashboardWidgetsMutation();+const onLayoutChange = (newLayout: Layout) => {if (!isEditing) {return;}- send(- 'dashboard-update',- newLayout.map(item => ({+ updateDashboardWidgetsMutation.mutate({+ widgets: newLayout.map(item => ({id: item.i,width: item.w,height: item.h,x: item.x,y: item.y,})),- );+ });};- const onAddWidget = <T extends Widget>(+ const addDashboardWidgetMutation = useAddDashboardWidgetMutation();++ const onAddWidget = <T extends DashboardWidgetEntity>(type: T['type'],meta: T['meta'] = null,) => {- send('dashboard-add-widget', {- type,- width: 4,- height: 2,- meta,- dashboard_page_id: dashboard.id,+ addDashboardWidgetMutation.mutate({+ widget: {+ type,+ width: 4,+ height: 2,+ meta,+ dashboard_page_id: dashboard.id,+ },});};+ const removeDashboardWidgetMutation = useRemoveDashboardWidgetMutation();+const onRemoveWidget = (widgetId: string) => {- send('dashboard-remove-widget', widgetId);+ removeDashboardWidgetMutation.mutate({ id: widgetId });};const onExport = () => {@@ -283,6 +314,9 @@ export function Overview({ dashboard }: OverviewProps) {t('Export Dashboard'),);};++ const importDashboardPageMutation = useImportDashboardPageMutation();+const onImport = async () => {const openFileDialog = window.Actual.openFileDialog;@@ -300,7 +334,7 @@ export function Overview({ dashboard }: OverviewProps) {return;}- const [filepath] = await openFileDialog({+ const [filePath] = await openFileDialog({properties: ['openFile'],filters: [{@@ -312,82 +346,107 @@ export function Overview({ dashboard }: OverviewProps) {closeNotifications();setIsImporting(true);- const res = await send('dashboard-import', {- filepath,- dashboardPageId: dashboard.id,- });- setIsImporting(false);-- if ('error' in res) {- switch (res.error) {- case 'json-parse-error':- dispatch(- addNotification({- notification: {- id: 'import',- type: 'error',- message: t('Failed parsing the imported JSON.'),- },- }),- );- break;-- case 'validation-error':- dispatch(- addNotification({- notification: {- id: 'import',- type: 'error',- message: res.message,- },- }),- );- break;-- default:- dispatch(- addNotification({- notification: {- id: 'import',- type: 'error',- message: t('Failed importing the dashboard file.'),- },- }),- );- break;- }- return;- }- onDispatchSucessNotification(- t(- "Dashboard has been successfully imported. Don't like what you see? You can always press [ctrl+z](#undo) to undo.",- ),+ importDashboardPageMutation.mutate(+ {+ filePath,+ dashboardPageId: dashboard.id,+ },+ {+ onSettled: () => {+ setIsImporting(false);+ },+ onSuccess: () => {+ onDispatchSucessNotification(+ t(+ "Dashboard has been successfully imported. Don't like what you see? You can always press [ctrl+z](#undo) to undo.",+ ),+ );+ },+ onError: error => {+ const originalError = error.cause;+ if (originalError instanceof Error) {+ switch (originalError.cause) {+ case 'json-parse-error':+ dispatch(+ addNotification({+ notification: {+ id: 'import',+ type: 'error',+ message: t('Failed parsing the imported JSON.'),+ },+ }),+ );+ break;++ case 'validation-error':+ dispatch(+ addNotification({+ notification: {+ id: 'import',+ type: 'error',+ message: error.message,+ },+ }),+ );+ break;++ default:+ dispatch(+ addNotification({+ notification: {+ id: 'import',+ type: 'error',+ message: t('Failed importing the dashboard file.'),+ },+ }),+ );+ break;+ }+ }+ },+ },);};- const onMetaChange = (widget: { i: string }, newMeta: Widget['meta']) => {- send('dashboard-update-widget', {- id: widget.i,- meta: newMeta,+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();++ const onMetaChange = (+ widget: { i: string },+ newMeta: DashboardWidgetEntity['meta'],+ ) => {+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.i,+ meta: newMeta,+ },});};+ const copyDashboardWidgetMutation = useCopyDashboardWidgetMutation();+const onCopyWidget = (widgetId: string, targetDashboardId: string) => {- send('dashboard-copy-widget', {- widgetId,+ copyDashboardWidgetMutation.mutate({+ id: widgetId,targetDashboardPageId: targetDashboardId,});};- const onDeleteDashboard = async (id: string) => {- await send('dashboard-delete', id);+ const deleteDashboardPageMutation = useDeleteDashboardPageMutation();- const next_dashboard = dashboard_pages.find(d => d.id !== id);- // NOTE: This should hold since invariant dashboard_pages > 1- if (next_dashboard) {- navigate(`/reports/${next_dashboard.id}`);- }+ const onDeleteDashboard = async (id: string) => {+ deleteDashboardPageMutation.mutate(+ { id },+ {+ onSuccess: () => {+ const nextDashboard = dashboardPages.find(d => d.id !== id);+ // NOTE: This should hold since invariant dashboard_pages > 1+ if (nextDashboard) {+ navigate(`/reports/${nextDashboard.id}`);+ }+ },+ },+ );};const accounts = useAccounts();@@ -421,7 +480,7 @@ export function Overview({ dashboard }: OverviewProps) {}}><DashboardSelector- dashboards={dashboard_pages}+ dashboards={dashboardPages}currentDashboard={dashboard}/></View>@@ -449,7 +508,7 @@ export function Overview({ dashboard }: OverviewProps) {<>{/* Dashboard Selector */}<DashboardSelector- dashboards={dashboard_pages}+ dashboards={dashboardPages}currentDashboard={dashboard}/>@@ -638,7 +697,7 @@ export function Overview({ dashboard }: OverviewProps) {name: 'delete',text: t('Delete dashboard'),disabled:- isImporting || dashboard_pages.length <= 1,+ isImporting || dashboardPages.length <= 1,},]}/>diff --git a/packages/desktop-client/src/components/reports/ReportsDashboardRouter.tsx b/packages/desktop-client/src/components/reports/ReportsDashboardRouter.tsxindex 9ed7f1f23f..0c39da49c3 100644--- a/packages/desktop-client/src/components/reports/ReportsDashboardRouter.tsx+++ b/packages/desktop-client/src/components/reports/ReportsDashboardRouter.tsx@@ -8,30 +8,30 @@ import { View } from '@actual-app/components/view';import { LoadingIndicator } from './LoadingIndicator';import { Overview } from './Overview';-import { useDashboardPages } from '@desktop-client/hooks/useDashboard';+import { useDashboardPages } from '@desktop-client/hooks/useDashboardPages';import { useNavigate } from '@desktop-client/hooks/useNavigate';export function ReportsDashboardRouter() {const { t } = useTranslation();const { dashboardId } = useParams<{ dashboardId?: string }>();const navigate = useNavigate();- const { data: dashboard_pages, isLoading } = useDashboardPages();+ const { data: dashboardPages = [], isPending } = useDashboardPages();// Redirect to first dashboard if no dashboardId in URLuseEffect(() => {- if (!dashboardId && !isLoading && dashboard_pages.length > 0) {- navigate(`/reports/${dashboard_pages[0].id}`, { replace: true });+ if (!dashboardId && !isPending && dashboardPages.length > 0) {+ navigate(`/reports/${dashboardPages[0].id}`, { replace: true });}- }, [dashboardId, isLoading, dashboard_pages, navigate]);+ }, [dashboardId, isPending, dashboardPages, navigate]);// Show loading while we're fetching dashboards or redirecting- if (isLoading || (!dashboardId && dashboard_pages.length > 0)) {+ if (isPending || (!dashboardId && dashboardPages.length > 0)) {return <LoadingIndicator message={t('Loading dashboards...')} />;}// If we have a dashboardId, render Overview with itif (dashboardId) {- const dashboard = dashboard_pages.find(d => d.id === dashboardId);+ const dashboard = dashboardPages.find(d => d.id === dashboardId);if (dashboard) {return <Overview dashboard={dashboard} />;} else {diff --git a/packages/desktop-client/src/components/reports/SaveReport.tsx b/packages/desktop-client/src/components/reports/SaveReport.tsxindex 6138c830dc..c30fa21547 100644--- a/packages/desktop-client/src/components/reports/SaveReport.tsx+++ b/packages/desktop-client/src/components/reports/SaveReport.tsx@@ -9,10 +9,9 @@ import { SpaceBetween } from '@actual-app/components/space-between';import { Text } from '@actual-app/components/text';import { View } from '@actual-app/components/view';-import { send } from 'loot-core/platform/client/connection';import type {CustomReportEntity,- DashboardEntity,+ DashboardPageEntity,} from 'loot-core/types/models';import { LoadingIndicator } from './LoadingIndicator';@@ -23,9 +22,10 @@ import type { SavedStatus } from './SaveReportMenu';import { SaveReportName } from './SaveReportName';import { FormField, FormLabel } from '@desktop-client/components/forms';-import { useDashboardPages } from '@desktop-client/hooks/useDashboard';+import { useDashboardPages } from '@desktop-client/hooks/useDashboardPages';import { useReports } from '@desktop-client/hooks/useReports';import {+ useAddDashboardWidgetMutation,useCreateReportMutation,useDeleteReportMutation,useUpdateReportMutation,@@ -59,16 +59,16 @@ type SaveReportProps<T extends CustomReportEntity = CustomReportEntity> = {savedReport?: CustomReportEntity;},) => void;- dashboardPages: readonly DashboardEntity[];+ dashboardPages: readonly DashboardPageEntity[];};export function SaveReportWrapper<T extends CustomReportEntity = CustomReportEntity,>(props: Omit<SaveReportProps<T>, 'dashboardPages'>) {const { t } = useTranslation();- const { data, isLoading } = useDashboardPages();+ const { data = [], isPending } = useDashboardPages();- if (isLoading) {+ if (isPending) {return <LoadingIndicator message={t('Loading dashboards...')} />;}@@ -99,6 +99,7 @@ export function SaveReport({const createReportMutation = useCreateReportMutation();const updateReportMutation = useUpdateReportMutation();+ const addDashboardWidgetMutation = useAddDashboardWidgetMutation();async function onApply(cond: string) {const chooseSavedReport = listReports.find(r => cond === r.id);@@ -127,22 +128,29 @@ export function SaveReport({{ report: newSavedReport },{onSuccess: async id => {- await send('dashboard-add-widget', {- type: 'custom-report',- width: 4,- height: 2,- meta: { id },- dashboard_page_id: saveDashboardId,- });-- setNameMenuOpen(false);- onReportChange({- savedReport: {- ...newSavedReport,- id,+ addDashboardWidgetMutation.mutate(+ {+ widget: {+ type: 'custom-report',+ width: 4,+ height: 2,+ meta: { id },+ dashboard_page_id: saveDashboardId,+ },+ },+ {+ onSuccess: () => {+ setNameMenuOpen(false);+ onReportChange({+ savedReport: {+ ...newSavedReport,+ id,+ },+ type: 'add-update',+ });+ },},- type: 'add-update',- });+ );},onError: error => {setErr(error.message);diff --git a/packages/desktop-client/src/components/reports/reports/BudgetAnalysis.tsx b/packages/desktop-client/src/components/reports/reports/BudgetAnalysis.tsxindex 4ece950aa2..5badea9343 100644--- a/packages/desktop-client/src/components/reports/reports/BudgetAnalysis.tsx+++ b/packages/desktop-client/src/components/reports/reports/BudgetAnalysis.tsx@@ -38,23 +38,24 @@ import { calculateTimeRange } from '@desktop-client/components/reports/reportRanimport { createBudgetAnalysisSpreadsheet } from '@desktop-client/components/reports/spreadsheets/budget-analysis-spreadsheet';import { useReport } from '@desktop-client/components/reports/useReport';import { fromDateRepr } from '@desktop-client/components/reports/util';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';import { useFormat } from '@desktop-client/hooks/useFormat';import { useLocale } from '@desktop-client/hooks/useLocale';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useRuleConditionFilters } from '@desktop-client/hooks/useRuleConditionFilters';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';-import { useWidget } from '@desktop-client/hooks/useWidget';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';export function BudgetAnalysis() {const params = useParams();- const { data: widget, isLoading } = useWidget<BudgetAnalysisWidget>(- params.id ?? '',- 'budget-analysis-card',- );+ const { data: widget, isPending } = useDashboardWidget<BudgetAnalysisWidget>({+ id: params.id,+ type: 'budget-analysis-card',+ });- if (isLoading) {+ if (isPending) {return <LoadingIndicator />;}@@ -207,33 +208,43 @@ function BudgetAnalysisInternal({ widget }: BudgetAnalysisInternalProps) {setIsConcise(calculateIsConcise(newStart, newEnd));};+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();+async function onSaveWidget() {if (!widget) {throw new Error('No widget that could be saved.');}- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- conditions,- conditionsOp,- timeFrame: {- start,- end,- mode,+ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ conditions,+ conditionsOp,+ timeFrame: {+ start,+ end,+ mode,+ },+ graphType,+ showBalance,+ },},- graphType,- showBalance,},- });- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Dashboard widget successfully saved.'),+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );},- }),+ },);}@@ -245,17 +256,20 @@ function BudgetAnalysisInternal({ widget }: BudgetAnalysisInternalProps) {const endingBalance = latestInterval?.balance ?? 0;const title = widget?.meta?.name || t('Budget Analysis');+const onSaveWidgetName = async (newName: string) => {if (!widget) {throw new Error('No widget that could be saved.');}const name = newName || t('Budget Analysis');- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- name,+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ },},});};diff --git a/packages/desktop-client/src/components/reports/reports/BudgetAnalysisCard.tsx b/packages/desktop-client/src/components/reports/reports/BudgetAnalysisCard.tsxindex 7000d7a266..a5e8fa5c28 100644--- a/packages/desktop-client/src/components/reports/reports/BudgetAnalysisCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/BudgetAnalysisCard.tsx@@ -18,8 +18,8 @@ import { ReportCard } from '@desktop-client/components/reports/ReportCard';import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';import { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';import { createBudgetAnalysisSpreadsheet } from '@desktop-client/components/reports/spreadsheets/budget-analysis-spreadsheet';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { useReport } from '@desktop-client/components/reports/useReport';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';import { useFormat } from '@desktop-client/hooks/useFormat';type BudgetAnalysisCardProps = {@@ -46,7 +46,7 @@ export function BudgetAnalysisCard({const [nameMenuOpen, setNameMenuOpen] = useState(false);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);const timeFrame = meta?.timeFrame ?? {start: monthUtils.subMonths(monthUtils.currentMonth(), 5),diff --git a/packages/desktop-client/src/components/reports/reports/Calendar.tsx b/packages/desktop-client/src/components/reports/reports/Calendar.tsxindex 5c91582535..c0ddffd5b8 100644--- a/packages/desktop-client/src/components/reports/reports/Calendar.tsx+++ b/packages/desktop-client/src/components/reports/reports/Calendar.tsx@@ -55,6 +55,7 @@ import { TransactionList } from '@desktop-client/components/transactions/Transacimport { useAccounts } from '@desktop-client/hooks/useAccounts';import { SchedulesProvider } from '@desktop-client/hooks/useCachedSchedules';import { useCategories } from '@desktop-client/hooks/useCategories';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';import { useDateFormat } from '@desktop-client/hooks/useDateFormat';import { DisplayPayeeProvider } from '@desktop-client/hooks/useDisplayPayee';import { useFormat } from '@desktop-client/hooks/useFormat';@@ -69,9 +70,9 @@ import { SelectedProviderWithItems } from '@desktop-client/hooks/useSelected';import { SplitsExpandedProvider } from '@desktop-client/hooks/useSplitsExpanded';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';import { useTransactions } from '@desktop-client/hooks/useTransactions';-import { useWidget } from '@desktop-client/hooks/useWidget';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';const CHEVRON_HEIGHT = 42;const SUMMARY_HEIGHT = 140;@@ -79,12 +80,12 @@ const SUMMARY_HEIGHT = 140;export function Calendar() {const params = useParams();const [searchParams] = useSearchParams();- const { data: widget, isLoading } = useWidget<CalendarWidget>(- params.id ?? '',- 'calendar-card',- );+ const { data: widget, isPending } = useDashboardWidget<CalendarWidget>({+ id: params.id,+ type: 'calendar-card',+ });- if (isLoading) {+ if (isPending) {return <LoadingIndicator />;}@@ -326,6 +327,7 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {const title = widget?.meta?.name || t('Calendar');const table = useRef<TableHandleRef<TransactionEntity>>(null);const dateFormat = useDateFormat();+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();const onSaveWidgetName = async (newName: string) => {if (!widget) {@@ -333,11 +335,13 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {}const name = newName || t('Calendar');- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- name,+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ },},});};@@ -353,39 +357,46 @@ function CalendarInner({ widget, parameters }: CalendarInnerProps) {throw new Error('No widget that could be saved.');}- try {- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- conditions,- conditionsOp,- timeFrame: {- start,- end,- mode,+ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ conditions,+ conditionsOp,+ timeFrame: {+ start,+ end,+ mode,+ },},},- });- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Dashboard widget successfully saved.'),- },- }),- );- } catch (error) {- dispatch(- addNotification({- notification: {- type: 'error',- message: t('Failed to save dashboard widget.'),- },- }),- );- console.error('Error saving widget:', error);- }+ },+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );+ },+ onError: error => {+ dispatch(+ addNotification({+ notification: {+ type: 'error',+ message: t('Failed to save dashboard widget.'),+ },+ }),+ );+ console.error('Error saving widget:', error);+ },+ },+ );}const { totalIncome, totalExpense } = useMemo(() => {if (!data || !data.calendarData) {diff --git a/packages/desktop-client/src/components/reports/reports/CalendarCard.tsx b/packages/desktop-client/src/components/reports/reports/CalendarCard.tsxindex 8b4832250e..b50f1d3c23 100644--- a/packages/desktop-client/src/components/reports/reports/CalendarCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/CalendarCard.tsx@@ -37,8 +37,8 @@ import { ReportCardName } from '@desktop-client/components/reports/ReportCardNamimport { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';import { calendarSpreadsheet } from '@desktop-client/components/reports/spreadsheets/calendar-spreadsheet';import type { CalendarDataType } from '@desktop-client/components/reports/spreadsheets/calendar-spreadsheet';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { useReport } from '@desktop-client/components/reports/useReport';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';import { useFormat } from '@desktop-client/hooks/useFormat';import type { FormatType } from '@desktop-client/hooks/useFormat';import { useMergedRefs } from '@desktop-client/hooks/useMergedRefs';@@ -169,7 +169,7 @@ export function CalendarCard({}, [data]);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);return (<ReportCarddiff --git a/packages/desktop-client/src/components/reports/reports/CashFlow.tsx b/packages/desktop-client/src/components/reports/reports/CashFlow.tsxindex 76571520ad..6711417f2b 100644--- a/packages/desktop-client/src/components/reports/reports/CashFlow.tsx+++ b/packages/desktop-client/src/components/reports/reports/CashFlow.tsx@@ -36,14 +36,15 @@ import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndiimport { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';import { cashFlowByDate } from '@desktop-client/components/reports/spreadsheets/cash-flow-spreadsheet';import { useReport } from '@desktop-client/components/reports/useReport';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';import { useFormat } from '@desktop-client/hooks/useFormat';import { useLocale } from '@desktop-client/hooks/useLocale';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useRuleConditionFilters } from '@desktop-client/hooks/useRuleConditionFilters';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';-import { useWidget } from '@desktop-client/hooks/useWidget';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';export const defaultTimeFrame = {start: monthUtils.dayFromDate(monthUtils.currentMonth()),@@ -53,12 +54,12 @@ export const defaultTimeFrame = {export function CashFlow() {const params = useParams();- const { data: widget, isLoading } = useWidget<CashFlowWidget>(- params.id ?? '',- 'cash-flow-card',- );+ const { data: widget, isPending } = useDashboardWidget<CashFlowWidget>({+ id: params.id,+ type: 'cash-flow-card',+ });- if (isLoading) {+ if (isPending) {return <LoadingIndicator />;}@@ -186,33 +187,42 @@ function CashFlowInner({ widget }: CashFlowInnerProps) {const navigate = useNavigate();const { isNarrowWidth } = useResponsive();+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();async function onSaveWidget() {if (!widget) {throw new Error('No widget that could be saved.');}- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- conditions,- conditionsOp,- timeFrame: {- start,- end,- mode,+ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ conditions,+ conditionsOp,+ timeFrame: {+ start,+ end,+ mode,+ },+ showBalance,+ },},- showBalance,},- });- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Dashboard widget successfully saved.'),+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );},- }),+ },);}@@ -223,11 +233,13 @@ function CashFlowInner({ widget }: CashFlowInnerProps) {}const name = newName || t('Cash Flow');- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- name,+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ },},});};diff --git a/packages/desktop-client/src/components/reports/reports/CashFlowCard.tsx b/packages/desktop-client/src/components/reports/reports/CashFlowCard.tsxindex 34aa80219a..ee8f216768 100644--- a/packages/desktop-client/src/components/reports/reports/CashFlowCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/CashFlowCard.tsx@@ -23,8 +23,8 @@ import { ReportCard } from '@desktop-client/components/reports/ReportCard';import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';import { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';import { simpleCashFlow } from '@desktop-client/components/reports/spreadsheets/cash-flow-spreadsheet';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { useReport } from '@desktop-client/components/reports/useReport';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';import { useFormat } from '@desktop-client/hooks/useFormat';type CustomLabelProps = {@@ -116,7 +116,7 @@ export function CashFlowCard({const [nameMenuOpen, setNameMenuOpen] = useState(false);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);useEffect(() => {async function fetchLatestTransaction() {diff --git a/packages/desktop-client/src/components/reports/reports/Crossover.tsx b/packages/desktop-client/src/components/reports/reports/Crossover.tsxindex 4265cf15b7..a8baad2a53 100644--- a/packages/desktop-client/src/components/reports/reports/Crossover.tsx+++ b/packages/desktop-client/src/components/reports/reports/Crossover.tsx@@ -45,13 +45,14 @@ import type { CrossoverData } from '@desktop-client/components/reports/spreadsheimport { useReport } from '@desktop-client/components/reports/useReport';import { useAccounts } from '@desktop-client/hooks/useAccounts';import { useCategories } from '@desktop-client/hooks/useCategories';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';import { useFormat } from '@desktop-client/hooks/useFormat';import { useLocale } from '@desktop-client/hooks/useLocale';import { useNavigate } from '@desktop-client/hooks/useNavigate';import type { useSpreadsheet } from '@desktop-client/hooks/useSpreadsheet';-import { useWidget } from '@desktop-client/hooks/useWidget';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';export const defaultTimeFrame = {start: monthUtils.subMonths(monthUtils.currentMonth(), 120),@@ -61,12 +62,12 @@ export const defaultTimeFrame = {export function Crossover() {const params = useParams();- const { data: widget, isLoading } = useWidget<CrossoverWidget>(- params.id ?? '',- 'crossover-card',- );+ const { data: widget, isPending } = useDashboardWidget<CrossoverWidget>({+ id: params.id,+ type: 'crossover-card',+ });- if (isLoading) {+ if (isPending) {return <LoadingIndicator />;}@@ -271,6 +272,8 @@ function CrossoverInner({ widget }: CrossoverInnerProps) {setMode(mode);}+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();+async function onSaveWidget() {if (!widget) {dispatch(@@ -284,30 +287,38 @@ function CrossoverInner({ widget }: CrossoverInnerProps) {return;}- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- expenseCategoryIds: selectedExpenseCategories.map(c => c.id),- incomeAccountIds: selectedIncomeAccountIds,- safeWithdrawalRate: swr,- estimatedReturn: useCustomGrowth ? (estimatedReturn ?? 0) : null,- expectedContribution: useCustomGrowth- ? (expectedContribution ?? 0)- : null,- projectionType,- expenseAdjustmentFactor,- showHiddenCategories,- timeFrame: { start, end, mode },+ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ expenseCategoryIds: selectedExpenseCategories.map(c => c.id),+ incomeAccountIds: selectedIncomeAccountIds,+ safeWithdrawalRate: swr,+ estimatedReturn: useCustomGrowth ? (estimatedReturn ?? 0) : null,+ expectedContribution: useCustomGrowth+ ? (expectedContribution ?? 0)+ : null,+ projectionType,+ expenseAdjustmentFactor,+ showHiddenCategories,+ timeFrame: { start, end, mode },+ },+ },},- });- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Dashboard widget successfully saved.'),+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );},- }),+ },);}@@ -391,11 +402,13 @@ function CrossoverInner({ widget }: CrossoverInnerProps) {}const name = newName || t('Crossover Point');- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- name,+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ },},});};diff --git a/packages/desktop-client/src/components/reports/reports/CrossoverCard.tsx b/packages/desktop-client/src/components/reports/reports/CrossoverCard.tsxindex 2ab41b902c..313b3db5a7 100644--- a/packages/desktop-client/src/components/reports/reports/CrossoverCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/CrossoverCard.tsx@@ -19,8 +19,8 @@ import { ReportCardName } from '@desktop-client/components/reports/ReportCardNamimport { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';import { createCrossoverSpreadsheet } from '@desktop-client/components/reports/spreadsheets/crossover-spreadsheet';import type { CrossoverData } from '@desktop-client/components/reports/spreadsheets/crossover-spreadsheet';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { useReport } from '@desktop-client/components/reports/useReport';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';import { useFormat } from '@desktop-client/hooks/useFormat';import { useLocale } from '@desktop-client/hooks/useLocale';@@ -50,7 +50,7 @@ export function CrossoverCard({const [nameMenuOpen, setNameMenuOpen] = useState(false);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);// Calculate date range from meta or use default rangeconst [start, setStart] = useState<string>('');diff --git a/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx b/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsxindex 0b3312c3e1..30d92899a9 100644--- a/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx+++ b/packages/desktop-client/src/components/reports/reports/CustomReportListCards.tsx@@ -18,7 +18,7 @@ import { MissingReportCard } from './MissingReportCard';import { DateRange } from '@desktop-client/components/reports/DateRange';import { ReportCard } from '@desktop-client/components/reports/ReportCard';import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { calculateHasWarning } from '@desktop-client/components/reports/util';import { useAccounts } from '@desktop-client/hooks/useAccounts';import { useCategories } from '@desktop-client/hooks/useCategories';@@ -78,7 +78,7 @@ function CustomReportListCardsInner({const [latestTransaction, setLatestTransaction] = useState('');const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);const payees = usePayees();const accounts = useAccounts();diff --git a/packages/desktop-client/src/components/reports/reports/Formula.tsx b/packages/desktop-client/src/components/reports/reports/Formula.tsxindex 7d7b9d4206..8b0b825a3d 100644--- a/packages/desktop-client/src/components/reports/reports/Formula.tsx+++ b/packages/desktop-client/src/components/reports/reports/Formula.tsx@@ -11,7 +11,6 @@ import { styles } from '@actual-app/components/styles';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';-import { send } from 'loot-core/platform/client/connection';import type { FormulaWidget } from 'loot-core/types/models';import { EditablePageHeaderTitle } from '@desktop-client/components/EditablePageHeaderTitle';@@ -24,12 +23,13 @@ import {} from '@desktop-client/components/Page';import { FormulaResult } from '@desktop-client/components/reports/FormulaResult';import { LoadingIndicator } from '@desktop-client/components/reports/LoadingIndicator';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';import { useFormulaExecution } from '@desktop-client/hooks/useFormulaExecution';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useThemeColors } from '@desktop-client/hooks/useThemeColors';-import { useWidget } from '@desktop-client/hooks/useWidget';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';const FormulaEditor = lazy(() =>import('../../formula/FormulaEditor').then(module => ({@@ -39,12 +39,12 @@ const FormulaEditor = lazy(() =>export function Formula() {const params = useParams();- const { data: widget, isLoading } = useWidget<FormulaWidget>(- params.id ?? '',- 'formula-card',- );+ const { data: widget, isPending } = useDashboardWidget<FormulaWidget>({+ id: params.id,+ type: 'formula-card',+ });- if (isLoading) {+ if (isPending) {return <LoadingIndicator />;}@@ -115,6 +115,8 @@ function FormulaInner({ widget }: FormulaInnerProps) {[],);+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();+const onSaveWidgetName = async (newName: string) => {if (!widget) {dispatch(@@ -129,16 +131,18 @@ function FormulaInner({ widget }: FormulaInnerProps) {}const name = newName || t('Formula');- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- name,- formula,- queries: queriesRef.current,- fontSizeMode,- staticFontSize,- colorFormula,+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ formula,+ queries: queriesRef.current,+ fontSizeMode,+ staticFontSize,+ colorFormula,+ },},});};@@ -156,25 +160,32 @@ function FormulaInner({ widget }: FormulaInnerProps) {return;}- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- formula,- queries: queriesRef.current,- fontSizeMode,- staticFontSize,- colorFormula,+ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ formula,+ queries: queriesRef.current,+ fontSizeMode,+ staticFontSize,+ colorFormula,+ },+ },},- });-- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Dashboard widget successfully saved.'),+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );},- }),+ },);}diff --git a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsxindex 9d4983092e..46c80c5c9a 100644--- a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx@@ -8,7 +8,7 @@ import type { FormulaWidget } from 'loot-core/types/models';import { FormulaResult } from '@desktop-client/components/reports/FormulaResult';import { ReportCard } from '@desktop-client/components/reports/ReportCard';import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { useFormulaExecution } from '@desktop-client/hooks/useFormulaExecution';import { useThemeColors } from '@desktop-client/hooks/useThemeColors';@@ -32,7 +32,7 @@ export function FormulaCard({const { t } = useTranslation();const [nameMenuOpen, setNameMenuOpen] = useState(false);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);const themeColors = useThemeColors();const containerRef = useRef<HTMLDivElement>(null);diff --git a/packages/desktop-client/src/components/reports/reports/MarkdownCard.tsx b/packages/desktop-client/src/components/reports/reports/MarkdownCard.tsxindex c0cb545d97..f8596bda38 100644--- a/packages/desktop-client/src/components/reports/reports/MarkdownCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/MarkdownCard.tsx@@ -15,7 +15,7 @@ import type { MarkdownWidget } from 'loot-core/types/models';import { NON_DRAGGABLE_AREA_CLASS_NAME } from '@desktop-client/components/reports/constants';import { ReportCard } from '@desktop-client/components/reports/ReportCard';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import {markdownBaseStyles,remarkBreaks,@@ -54,7 +54,7 @@ export function MarkdownCard({const [isVisibleTextArea, setIsVisibleTextArea] = useState(false);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);return (<ReportCarddiff --git a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx b/packages/desktop-client/src/components/reports/reports/NetWorth.tsxindex 86213b5228..ffd9893fe8 100644--- a/packages/desktop-client/src/components/reports/reports/NetWorth.tsx+++ b/packages/desktop-client/src/components/reports/reports/NetWorth.tsx@@ -42,21 +42,22 @@ import { createSpreadsheet as netWorthSpreadsheet } from '@desktop-client/componimport { useReport } from '@desktop-client/components/reports/useReport';import { fromDateRepr } from '@desktop-client/components/reports/util';import { useAccounts } from '@desktop-client/hooks/useAccounts';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';import { useFormat } from '@desktop-client/hooks/useFormat';import { useLocale } from '@desktop-client/hooks/useLocale';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useRuleConditionFilters } from '@desktop-client/hooks/useRuleConditionFilters';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';-import { useWidget } from '@desktop-client/hooks/useWidget';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';export function NetWorth() {const params = useParams();- const { data: widget, isLoading } = useWidget<NetWorthWidget>(- params.id ?? '',- 'net-worth-card',- );+ const { data: widget, isLoading } = useDashboardWidget<NetWorthWidget>({+ id: params.id,+ type: 'net-worth-card',+ });if (isLoading) {return <LoadingIndicator />;@@ -225,33 +226,43 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {setModeAndInterval(mode);}+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();+async function onSaveWidget() {if (!widget) {throw new Error('No widget that could be saved.');}- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- conditions,- conditionsOp,- interval,- mode: graphMode,- timeFrame: {- start,- end,- mode,+ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ conditions,+ conditionsOp,+ interval,+ mode: graphMode,+ timeFrame: {+ start,+ end,+ mode,+ },+ },},},- });- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Dashboard widget successfully saved.'),+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );},- }),+ },);}@@ -265,11 +276,13 @@ function NetWorthInner({ widget }: NetWorthInnerProps) {}const name = newName || t('Net Worth');- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- name,+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ },},});};diff --git a/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx b/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsxindex 584eb22317..c50d07a463 100644--- a/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/NetWorthCard.tsx@@ -20,8 +20,8 @@ import { ReportCard } from '@desktop-client/components/reports/ReportCard';import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';import { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';import { createSpreadsheet as netWorthSpreadsheet } from '@desktop-client/components/reports/spreadsheets/net-worth-spreadsheet';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { useReport } from '@desktop-client/components/reports/useReport';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';import { useFormat } from '@desktop-client/hooks/useFormat';import { useLocale } from '@desktop-client/hooks/useLocale';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';@@ -57,7 +57,7 @@ export function NetWorthCard({const [isCardHovered, setIsCardHovered] = useState(false);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);useEffect(() => {async function fetchLatestTransaction() {diff --git a/packages/desktop-client/src/components/reports/reports/Spending.tsx b/packages/desktop-client/src/components/reports/reports/Spending.tsxindex 6aa4f423af..19e4654f6a 100644--- a/packages/desktop-client/src/components/reports/reports/Spending.tsx+++ b/packages/desktop-client/src/components/reports/reports/Spending.tsx@@ -41,22 +41,23 @@ import { calculateSpendingReportTimeRange } from '@desktop-client/components/repimport { createSpendingSpreadsheet } from '@desktop-client/components/reports/spreadsheets/spending-spreadsheet';import { useReport } from '@desktop-client/components/reports/useReport';import { fromDateRepr } from '@desktop-client/components/reports/util';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';import { useFormat } from '@desktop-client/hooks/useFormat';import { useLocale } from '@desktop-client/hooks/useLocale';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useRuleConditionFilters } from '@desktop-client/hooks/useRuleConditionFilters';-import { useWidget } from '@desktop-client/hooks/useWidget';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';export function Spending() {const params = useParams();- const { data: widget, isLoading } = useWidget<SpendingWidget>(- params.id ?? '',- 'spending-card',- );+ const { data: widget, isPending } = useDashboardWidget<SpendingWidget>({+ id: params.id,+ type: 'spending-card',+ });- if (isLoading) {+ if (isPending) {return <LoadingIndicator />;}@@ -152,30 +153,40 @@ function SpendingInternal({ widget }: SpendingInternalProps) {const navigate = useNavigate();const { isNarrowWidth } = useResponsive();+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();+async function onSaveWidget() {if (!widget) {throw new Error('No widget that could be saved.');}- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- conditions,- conditionsOp,- compare,- compareTo,- isLive,- mode: reportMode,+ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ conditions,+ conditionsOp,+ compare,+ compareTo,+ isLive,+ mode: reportMode,+ },+ },},- });- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Dashboard widget successfully saved.'),+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );},- }),+ },);}@@ -210,11 +221,13 @@ function SpendingInternal({ widget }: SpendingInternalProps) {}const name = newName || t('Monthly Spending');- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- name,+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ },},});};diff --git a/packages/desktop-client/src/components/reports/reports/SpendingCard.tsx b/packages/desktop-client/src/components/reports/reports/SpendingCard.tsxindex beeacd5592..0c30150f60 100644--- a/packages/desktop-client/src/components/reports/reports/SpendingCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/SpendingCard.tsx@@ -18,8 +18,8 @@ import { ReportCard } from '@desktop-client/components/reports/ReportCard';import { ReportCardName } from '@desktop-client/components/reports/ReportCardName';import { calculateSpendingReportTimeRange } from '@desktop-client/components/reports/reportRanges';import { createSpendingSpreadsheet } from '@desktop-client/components/reports/spreadsheets/spending-spreadsheet';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { useReport } from '@desktop-client/components/reports/useReport';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';import { useFormat } from '@desktop-client/hooks/useFormat';type SpendingCardProps = {@@ -46,7 +46,7 @@ export function SpendingCard({const [nameMenuOpen, setNameMenuOpen] = useState(false);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);const spendingReportMode = meta?.mode ?? 'single-month';diff --git a/packages/desktop-client/src/components/reports/reports/Summary.tsx b/packages/desktop-client/src/components/reports/reports/Summary.tsxindex 4a6149ea96..ed7cba2c1a 100644--- a/packages/desktop-client/src/components/reports/reports/Summary.tsx+++ b/packages/desktop-client/src/components/reports/reports/Summary.tsx@@ -43,23 +43,24 @@ import { summarySpreadsheet } from '@desktop-client/components/reports/spreadsheimport { useReport } from '@desktop-client/components/reports/useReport';import { fromDateRepr } from '@desktop-client/components/reports/util';import { FieldSelect } from '@desktop-client/components/rules/RuleEditor';+import { useDashboardWidget } from '@desktop-client/hooks/useDashboardWidget';import { useFormat } from '@desktop-client/hooks/useFormat';import { useLocale } from '@desktop-client/hooks/useLocale';import { useNavigate } from '@desktop-client/hooks/useNavigate';import { useRuleConditionFilters } from '@desktop-client/hooks/useRuleConditionFilters';import { useSyncedPref } from '@desktop-client/hooks/useSyncedPref';-import { useWidget } from '@desktop-client/hooks/useWidget';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';+import { useUpdateDashboardWidgetMutation } from '@desktop-client/reports/mutations';export function Summary() {const params = useParams();- const { data: widget, isLoading } = useWidget<SummaryWidget>(- params.id ?? '',- 'summary-card',- );+ const { data: widget, isPending } = useDashboardWidget<SummaryWidget>({+ id: params.id,+ type: 'summary-card',+ });- if (isLoading) {+ if (isPending) {return <LoadingIndicator />;}@@ -234,6 +235,8 @@ function SummaryInner({ widget }: SummaryInnerProps) {const { isNarrowWidth } = useResponsive();const title = widget?.meta?.name || t('Summary');+ const updateDashboardWidgetMutation = useUpdateDashboardWidgetMutation();+const onSaveWidgetName = async (newName: string) => {if (!widget) {dispatch(@@ -248,12 +251,14 @@ function SummaryInner({ widget }: SummaryInnerProps) {}const name = newName || t('Summary');- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- name,- content: JSON.stringify(content),+ updateDashboardWidgetMutation.mutate({+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ name,+ content: JSON.stringify(content),+ },},});};@@ -276,27 +281,36 @@ function SummaryInner({ widget }: SummaryInnerProps) {);return;}- await send('dashboard-update-widget', {- id: widget.id,- meta: {- ...(widget.meta ?? {}),- conditions: dividendFilters.conditions,- conditionsOp: dividendFilters.conditionsOp,- timeFrame: {- start,- end,- mode,++ updateDashboardWidgetMutation.mutate(+ {+ widget: {+ id: widget.id,+ meta: {+ ...(widget.meta ?? {}),+ conditions: dividendFilters.conditions,+ conditionsOp: dividendFilters.conditionsOp,+ timeFrame: {+ start,+ end,+ mode,+ },+ content: JSON.stringify(content),+ },},- content: JSON.stringify(content),},- });- dispatch(- addNotification({- notification: {- type: 'message',- message: t('Dashboard widget successfully saved.'),+ {+ onSuccess: () => {+ dispatch(+ addNotification({+ notification: {+ type: 'message',+ message: t('Dashboard widget successfully saved.'),+ },+ }),+ );},- }),+ },);}diff --git a/packages/desktop-client/src/components/reports/reports/SummaryCard.tsx b/packages/desktop-client/src/components/reports/reports/SummaryCard.tsxindex 129203f845..c415dc1bee 100644--- a/packages/desktop-client/src/components/reports/reports/SummaryCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/SummaryCard.tsx@@ -14,8 +14,8 @@ import { ReportCardName } from '@desktop-client/components/reports/ReportCardNamimport { calculateTimeRange } from '@desktop-client/components/reports/reportRanges';import { summarySpreadsheet } from '@desktop-client/components/reports/spreadsheets/summary-spreadsheet';import { SummaryNumber } from '@desktop-client/components/reports/SummaryNumber';+import { useDashboardWidgetCopyMenu } from '@desktop-client/components/reports/useDashboardWidgetCopyMenu';import { useReport } from '@desktop-client/components/reports/useReport';-import { useWidgetCopyMenu } from '@desktop-client/components/reports/useWidgetCopyMenu';import { useLocale } from '@desktop-client/hooks/useLocale';type SummaryCardProps = {@@ -41,7 +41,7 @@ export function SummaryCard({const [nameMenuOpen, setNameMenuOpen] = useState(false);const { menuItems: copyMenuItems, handleMenuSelect: handleCopyMenuSelect } =- useWidgetCopyMenu(onCopy);+ useDashboardWidgetCopyMenu(onCopy);useEffect(() => {async function fetchLatestTransaction() {diff --git a/packages/desktop-client/src/components/reports/useWidgetCopyMenu.ts b/packages/desktop-client/src/components/reports/useDashboardWidgetCopyMenu.tssimilarity index 91%rename from packages/desktop-client/src/components/reports/useWidgetCopyMenu.tsrename to packages/desktop-client/src/components/reports/useDashboardWidgetCopyMenu.tsindex 9cb15afa6f..4426f67711 100644--- a/packages/desktop-client/src/components/reports/useWidgetCopyMenu.ts+++ b/packages/desktop-client/src/components/reports/useDashboardWidgetCopyMenu.ts@@ -6,16 +6,16 @@ import type { Menu } from '@actual-app/components/menu';import { pushModal } from '@desktop-client/modals/modalsSlice';import { useDispatch } from '@desktop-client/redux';-type WidgetCopyMenuResult = {+type DashboardWidgetCopyMenuResult = {/** Menu items to add to the card's menu */menuItems: ComponentProps<typeof Menu<string>>['items'];/** Handler for menu selection - call this from onMenuSelect */handleMenuSelect: (item: string) => boolean;};-export function useWidgetCopyMenu(+export function useDashboardWidgetCopyMenu(onCopy: (targetDashboardId: string) => void,-): WidgetCopyMenuResult {+): DashboardWidgetCopyMenuResult {const { t } = useTranslation();const dispatch = useDispatch();diff --git a/packages/desktop-client/src/hooks/useDashboard.ts b/packages/desktop-client/src/hooks/useDashboard.tsdeleted file mode 100644index cd8d3496d8..0000000000--- a/packages/desktop-client/src/hooks/useDashboard.ts+++ /dev/null@@ -1,37 +0,0 @@-import { useMemo } from 'react';--import { q } from 'loot-core/shared/query';-import type { DashboardEntity, Widget } from 'loot-core/types/models';--import { useQuery } from './useQuery';--export function useDashboard(dashboardPageId: string) {- const { data: queryData, isLoading } = useQuery<Widget>(() => {- return q('dashboard')- .filter({ dashboard_page_id: dashboardPageId })- .select('*');- }, [dashboardPageId]);-- return useMemo(- () => ({- isLoading,- data: queryData || [],- }),- [isLoading, queryData],- );-}--export function useDashboardPages() {- const { data: queryData, isLoading } = useQuery<DashboardEntity>(- () => q('dashboard_pages').select('*'),- [],- );-- return useMemo(- () => ({- isLoading,- data: queryData || [],- }),- [isLoading, queryData],- );-}diff --git a/packages/desktop-client/src/hooks/useDashboardPages.ts b/packages/desktop-client/src/hooks/useDashboardPages.tsnew file mode 100644index 0000000000..5af92f8004--- /dev/null+++ b/packages/desktop-client/src/hooks/useDashboardPages.ts@@ -0,0 +1,20 @@+import { useQuery } from '@tanstack/react-query';++import type {+ DashboardPageEntity,+ DashboardWidgetEntity,+} from 'loot-core/types/models';++import { dashboardQueries } from '@desktop-client/reports';++export function useDashboardPages() {+ return useQuery(dashboardQueries.listDashboardPages());+}++export function useDashboardPageWidgets<W extends DashboardWidgetEntity>(+ dashboardPageId?: DashboardPageEntity['id'] | null,+) {+ return useQuery(+ dashboardQueries.listDashboardPageWidgets<W>(dashboardPageId),+ );+}diff --git a/packages/desktop-client/src/hooks/useDashboardWidget.ts b/packages/desktop-client/src/hooks/useDashboardWidget.tsnew file mode 100644index 0000000000..db7e6b356b--- /dev/null+++ b/packages/desktop-client/src/hooks/useDashboardWidget.ts@@ -0,0 +1,20 @@+import { useQuery } from '@tanstack/react-query';++import type { DashboardWidgetEntity } from 'loot-core/types/models';++import { dashboardQueries } from '@desktop-client/reports';++type UseDashboardWidgetProps<W extends DashboardWidgetEntity> = Partial<+ Pick<W, 'id' | 'type'>+>;++export function useDashboardWidget<W extends DashboardWidgetEntity>({+ id,+ type,+}: UseDashboardWidgetProps<W>) {+ return useQuery({+ ...dashboardQueries.listDashboardWidgets<W>(),+ select: widgets => widgets.find(w => w.id === id && w.type === type),+ enabled: !!id && !!type,+ });+}diff --git a/packages/desktop-client/src/hooks/useWidget.ts b/packages/desktop-client/src/hooks/useWidget.tsdeleted file mode 100644index 6e049961bc..0000000000--- a/packages/desktop-client/src/hooks/useWidget.ts+++ /dev/null@@ -1,21 +0,0 @@-import { useMemo } from 'react';--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('*'),- [id, type],- );-- return useMemo(- () => ({- isLoading,- data: data?.[0],- }),- [data, isLoading],- );-}diff --git a/packages/desktop-client/src/reports/mutations.ts b/packages/desktop-client/src/reports/mutations.tsindex ff161d5343..f7ee5651d2 100644--- a/packages/desktop-client/src/reports/mutations.ts+++ b/packages/desktop-client/src/reports/mutations.ts@@ -6,10 +6,17 @@ import { v4 as uuidv4 } from 'uuid';import { sendCatch } from 'loot-core/platform/client/connection';import type { send } from 'loot-core/platform/client/connection';-import { logger } from 'loot-core/platform/server/log';-import type { CustomReportEntity } from 'loot-core/types/models';+import type {+ CustomReportEntity,+ DashboardPageEntity,+ DashboardWidgetEntity,+} from 'loot-core/types/models';+import type {+ EverythingButIdOptional,+ WithOptional,+} from 'loot-core/types/util';-import { reportQueries } from '.';+import { dashboardQueries, reportQueries } from './queries';import { addNotification } from '@desktop-client/notifications/notificationsSlice';import { useDispatch } from '@desktop-client/redux';@@ -23,12 +30,24 @@ const sendThrow: typeof send = async (name, args) => {return data;};-function invalidateQueries(queryClient: QueryClient, queryKey?: QueryKey) {+function invalidateReportQueries(+ queryClient: QueryClient,+ queryKey?: QueryKey,+) {queryClient.invalidateQueries({queryKey: queryKey ?? reportQueries.lists(),});}+function invalidateDashboardQueries(+ queryClient: QueryClient,+ queryKey?: QueryKey,+) {+ queryClient.invalidateQueries({+ queryKey: queryKey ?? dashboardQueries.lists(),+ });+}+function dispatchErrorNotification(dispatch: AppDispatch,message: string,@@ -46,6 +65,56 @@ function dispatchErrorNotification();}+type UpdateReportPayload = {+ report: CustomReportEntity;+};++export function useUpdateReportMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({ report }: UpdateReportPayload) => {+ return await sendThrow('report/update', report);+ },+ onSuccess: () => invalidateReportQueries(queryClient),+ onError: error => {+ console.error('Error updating report:', error);+ dispatchErrorNotification(+ dispatch,+ t('There was an error updating the report. Please try again.'),+ error,+ );+ },+ });+}++type DeleteReportPayload = {+ id: CustomReportEntity['id'];+};++export function useDeleteReportMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({ id }: DeleteReportPayload) => {+ return await sendThrow('report/delete', id);+ },+ onSuccess: () => invalidateReportQueries(queryClient),+ onError: error => {+ console.error('Error deleting report:', error);+ dispatchErrorNotification(+ dispatch,+ t('There was an error deleting the report. Please try again.'),+ error,+ );+ },+ });+}+type CreateReportMutationPayload = {report: CustomReportEntity;};@@ -59,9 +128,9 @@ export function useCreateReportMutation() {mutationFn: async ({ report }: CreateReportMutationPayload) => {return await sendThrow('report/create', report);},- onSuccess: () => invalidateQueries(queryClient),+ onSuccess: () => invalidateReportQueries(queryClient),onError: error => {- logger.error('Error creating report:', error);+ console.error('Error creating report:', error);dispatchErrorNotification(dispatch,t('There was an error creating the report. Please try again.'),@@ -71,50 +140,271 @@ export function useCreateReportMutation() {});}-type UpdateReportPayload = {- report: CustomReportEntity;+type CreateDashboardPageMutationPayload = {+ name: DashboardPageEntity['name'];};-export function useUpdateReportMutation() {+export function useCreateDashboardPageMutation() {const queryClient = useQueryClient();const dispatch = useDispatch();const { t } = useTranslation();return useMutation({- mutationFn: async ({ report }: UpdateReportPayload) => {- return await sendThrow('report/update', report);+ mutationFn: async ({ name }: CreateDashboardPageMutationPayload) => {+ return await sendThrow('dashboard-create', { name });},- onSuccess: () => invalidateQueries(queryClient),+ onSuccess: () => invalidateDashboardQueries(queryClient),onError: error => {- logger.error('Error updating report:', error);+ console.error('Error creating dashboard page:', error);dispatchErrorNotification(dispatch,- t('There was an error updating the report. Please try again.'),+ t('There was an error creating the dashboard page. Please try again.'),error,);},});}-type DeleteReportPayload = {- id: CustomReportEntity['id'];+type DeleteDashboardPageMutationPayload = {+ id: DashboardPageEntity['id'];};-export function useDeleteReportMutation() {+export function useDeleteDashboardPageMutation() {const queryClient = useQueryClient();const dispatch = useDispatch();const { t } = useTranslation();return useMutation({- mutationFn: async ({ id }: DeleteReportPayload) => {- return await sendThrow('report/delete', id);+ mutationFn: async ({ id }: DeleteDashboardPageMutationPayload) => {+ return await sendThrow('dashboard-delete', id);},- onSuccess: () => invalidateQueries(queryClient),+ onSuccess: () => invalidateDashboardQueries(queryClient),onError: error => {- logger.error('Error deleting report:', error);+ console.error('Error deleting dashboard page:', error);dispatchErrorNotification(dispatch,- t('There was an error deleting the report. Please try again.'),+ t('There was an error deleting the dashboard page. Please try again.'),+ error,+ );+ },+ });+}++type RenameDashboardPageMutationPayload = {+ id: DashboardPageEntity['id'];+ name: DashboardPageEntity['name'];+};++export function useRenameDashboardPageMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({ id, name }: RenameDashboardPageMutationPayload) => {+ return await sendThrow('dashboard-rename', { id, name });+ },+ onSuccess: () => invalidateDashboardQueries(queryClient),+ onError: error => {+ console.error('Error renaming dashboard page:', error);+ dispatchErrorNotification(+ dispatch,+ t('There was an error renaming the dashboard page. Please try again.'),+ error,+ );+ },+ });+}++type UpdateDashboardWidgetsMutationPayload = {+ widgets: EverythingButIdOptional<Omit<DashboardWidgetEntity, 'tombstone'>>[];+};++export function useUpdateDashboardWidgetsMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({ widgets }: UpdateDashboardWidgetsMutationPayload) => {+ return await sendThrow('dashboard-update', widgets);+ },+ onSuccess: () => invalidateDashboardQueries(queryClient),+ onError: error => {+ console.error('Error updating dashboard widgets:', error);+ dispatchErrorNotification(+ dispatch,+ t(+ 'There was an error updating the dashboard widgets. Please try again.',+ ),+ error,+ );+ },+ });+}++type UpdateDashboardWidgetMutationPayload = {+ widget: EverythingButIdOptional<Omit<DashboardWidgetEntity, 'tombstone'>>;+};++export function useUpdateDashboardWidgetMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({ widget }: UpdateDashboardWidgetMutationPayload) => {+ return await sendThrow('dashboard-update-widget', widget);+ },+ onSuccess: () => invalidateDashboardQueries(queryClient),+ onError: error => {+ console.error('Error updating dashboard widget:', error);+ dispatchErrorNotification(+ dispatch,+ t(+ 'There was an error updating the dashboard widget. Please try again.',+ ),+ error,+ );+ },+ });+}++type ResetDashboardPageMutationPayload = {+ id: DashboardPageEntity['id'];+};++export function useResetDashboardPageMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({ id }: ResetDashboardPageMutationPayload) => {+ return await sendThrow('dashboard-reset', id);+ },+ onSuccess: () => invalidateDashboardQueries(queryClient),+ onError: error => {+ console.error('Error resetting dashboard page:', error);+ dispatchErrorNotification(+ dispatch,+ t('There was an error resetting the dashboard page. Please try again.'),+ error,+ );+ },+ });+}++type AddDashboardWidgetMutationPayload = {+ widget: WithOptional<+ Omit<DashboardWidgetEntity, 'id' | 'tombstone'>,+ 'x' | 'y'+ >;+};++export function useAddDashboardWidgetMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({ widget }: AddDashboardWidgetMutationPayload) => {+ return await sendThrow('dashboard-add-widget', widget);+ },+ onSuccess: () => invalidateDashboardQueries(queryClient),+ onError: error => {+ console.error('Error adding dashboard widget:', error);+ dispatchErrorNotification(+ dispatch,+ t('There was an error adding the dashboard widget. Please try again.'),+ error,+ );+ },+ });+}++type RemoveDashboardWidgetMutationPayload = {+ id: DashboardWidgetEntity['id'];+};++export function useRemoveDashboardWidgetMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({ id }: RemoveDashboardWidgetMutationPayload) => {+ return await sendThrow('dashboard-remove-widget', id);+ },+ onSuccess: () => invalidateDashboardQueries(queryClient),+ onError: error => {+ console.error('Error removing dashboard widget:', error);+ dispatchErrorNotification(+ dispatch,+ t(+ 'There was an error removing the dashboard widget. Please try again.',+ ),+ error,+ );+ },+ });+}++type CopyDashboardWidgetMutationPayload = {+ id: DashboardWidgetEntity['id'];+ targetDashboardPageId: DashboardPageEntity['id'];+};++export function useCopyDashboardWidgetMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({+ id,+ targetDashboardPageId,+ }: CopyDashboardWidgetMutationPayload) => {+ return await sendThrow('dashboard-copy-widget', {+ id,+ targetDashboardPageId,+ });+ },+ onSuccess: () => invalidateDashboardQueries(queryClient),+ onError: error => {+ console.error('Error copying dashboard widget:', error);+ dispatchErrorNotification(+ dispatch,+ t('There was an error copying the dashboard widget. Please try again.'),+ error,+ );+ },+ });+}++type ImportDashboardPageMutationPayload = {+ filePath: string;+ dashboardPageId: DashboardPageEntity['id'];+};++export function useImportDashboardPageMutation() {+ const queryClient = useQueryClient();+ const dispatch = useDispatch();+ const { t } = useTranslation();++ return useMutation({+ mutationFn: async ({+ filePath,+ dashboardPageId,+ }: ImportDashboardPageMutationPayload) => {+ return await sendThrow('dashboard-import', { filePath, dashboardPageId });+ },+ onSuccess: () => invalidateDashboardQueries(queryClient),+ onError: error => {+ console.error('Error importing dashboard page:', error);+ dispatchErrorNotification(+ dispatch,+ t('There was an error importing the dashboard page. Please try again.'),error,);},diff --git a/packages/desktop-client/src/reports/queries.ts b/packages/desktop-client/src/reports/queries.tsindex c06f080351..a4e73d2137 100644--- a/packages/desktop-client/src/reports/queries.ts+++ b/packages/desktop-client/src/reports/queries.ts@@ -1,7 +1,14 @@import { queryOptions } from '@tanstack/react-query';import { send } from 'loot-core/platform/client/connection';-import type { CustomReportEntity } from 'loot-core/types/models';+import { q } from 'loot-core/shared/query';+import type {+ CustomReportEntity,+ DashboardPageEntity,+ DashboardWidgetEntity,+} from 'loot-core/types/models';++import { aqlQuery } from '@desktop-client/queries/aqlQuery';export const reportQueries = {all: () => ['reports'],@@ -14,3 +21,37 @@ export const reportQueries = {},}),};++export const dashboardQueries = {+ all: () => ['dashboards'],+ lists: () => [...dashboardQueries.all(), 'lists'],+ listDashboardWidgets: <T extends DashboardWidgetEntity>() =>+ queryOptions<T[]>({+ queryKey: [...dashboardQueries.lists(), 'widgets'],+ queryFn: async () => {+ const { data }: { data: T[] } = await aqlQuery(+ q('dashboard').select('*'),+ );+ return data;+ },+ }),+ listDashboardPageWidgets: <T extends DashboardWidgetEntity>(+ dashboardPageId?: DashboardPageEntity['id'] | null,+ ) =>+ queryOptions<T[]>({+ ...dashboardQueries.listDashboardWidgets<T>(),+ select: widgets =>+ widgets.filter(w => w.dashboard_page_id === dashboardPageId),+ enabled: !!dashboardPageId,+ }),+ listDashboardPages: () =>+ queryOptions<DashboardPageEntity[]>({+ queryKey: [...dashboardQueries.lists(), 'pages'],+ queryFn: async () => {+ const { data }: { data: DashboardPageEntity[] } = await aqlQuery(+ q('dashboard_pages').select('*'),+ );+ return data;+ },+ }),+};diff --git a/packages/loot-core/src/platform/client/connection/index-types.ts b/packages/loot-core/src/platform/client/connection/index-types.tsindex a8f4e4a67d..ef2b62e98a 100644--- a/packages/loot-core/src/platform/client/connection/index-types.ts+++ b/packages/loot-core/src/platform/client/connection/index-types.ts@@ -23,7 +23,11 @@ export declare function send<K extends keyof Handlers>(| { data: Awaited<ReturnType<Handlers[K]>>; error: undefined }| {data: undefined;- error: { type: 'APIError' | 'InternalError'; message: string };+ error: {+ type: 'APIError' | 'InternalError';+ message: string;+ cause?: unknown;+ };}>;export declare function send<K extends keyof Handlers>(@@ -48,7 +52,11 @@ export declare function sendCatch<K extends keyof Handlers>(| { data: Awaited<ReturnType<Handlers[K]>>; error: undefined }| {data: undefined;- error: { type: 'APIError' | 'InternalError'; message: string };+ error: {+ type: 'APIError' | 'InternalError';+ message: string;+ cause?: unknown;+ };}>;export type SendCatch = typeof sendCatch;diff --git a/packages/loot-core/src/platform/server/connection/index.electron.ts b/packages/loot-core/src/platform/server/connection/index.electron.tsindex 874e84db27..b13701019d 100644--- a/packages/loot-core/src/platform/server/connection/index.electron.ts+++ b/packages/loot-core/src/platform/server/connection/index.electron.ts@@ -11,7 +11,7 @@ function coerceError(error) {return error;}- return { type: 'InternalError', message: error.message };+ return { type: 'InternalError', message: error.message, cause: error };}export const init: T.Init = function (_socketName, handlers) {diff --git a/packages/loot-core/src/platform/server/connection/index.ts b/packages/loot-core/src/platform/server/connection/index.tsindex a768c86ead..ef0c4b91f6 100644--- a/packages/loot-core/src/platform/server/connection/index.ts+++ b/packages/loot-core/src/platform/server/connection/index.ts@@ -28,7 +28,7 @@ function coerceError(error) {return error;}- return { type: 'InternalError', message: error.message };+ return { type: 'InternalError', message: error.message, cause: error };}export const init: T.Init = function (serverChn, handlers) {diff --git a/packages/loot-core/src/server/dashboard/app.ts b/packages/loot-core/src/server/dashboard/app.tsindex 2906150423..b8d7b4fb3b 100644--- a/packages/loot-core/src/server/dashboard/app.ts+++ b/packages/loot-core/src/server/dashboard/app.ts@@ -6,12 +6,12 @@ import * as fs from '../../platform/server/fs';import { DEFAULT_DASHBOARD_STATE } from '../../shared/dashboard';import { q } from '../../shared/query';import type {+ DashboardWidgetEntity,ExportImportCustomReportWidget,ExportImportDashboard,ExportImportDashboardWidget,- Widget,} from '../../types/models';-import type { EverythingButIdOptional } from '../../types/util';+import type { EverythingButIdOptional, WithOptional } from '../../types/util';import { createApp } from '../app';import { aqlQuery } from '../aql';import * as db from '../db';@@ -28,7 +28,7 @@ function isExportedCustomReportWidget(return widget.type === 'custom-report';}-function isWidgetType(type: string): type is Widget['type'] {+function isWidgetType(type: string): type is DashboardWidgetEntity['type'] {return ['net-worth-card','cash-flow-card',@@ -100,10 +100,6 @@ const exportModel = {},};-async function getDashboardPages() {- return db.all('SELECT * FROM dashboard_pages WHERE tombstone = 0');-}-async function createDashboardPage({ name }: { name: string }) {const id = uuidv4();await db.insertWithSchema('dashboard_pages', { id, name });@@ -139,7 +135,7 @@ async function renameDashboardPage({ id, name }: { id: string; name: string }) {}async function updateDashboard(- widgets: EverythingButIdOptional<Omit<Widget, 'tombstone'>>[],+ widgets: EverythingButIdOptional<Omit<DashboardWidgetEntity, 'tombstone'>>[],) {const { data: dbWidgets } = await aqlQuery(q('dashboard')@@ -147,7 +143,7 @@ async function updateDashboard(.select('*'),);const dbWidgetMap = new Map(- (dbWidgets as Widget[]).map(widget => [widget.id, widget]),+ (dbWidgets as DashboardWidgetEntity[]).map(widget => [widget.id, widget]),);await Promise.all(@@ -159,7 +155,7 @@ async function updateDashboard(}async function updateDashboardWidget(- widget: EverythingButIdOptional<Omit<Widget, 'tombstone'>>,+ widget: EverythingButIdOptional<Omit<DashboardWidgetEntity, 'tombstone'>>,) {await db.updateWithSchema('dashboard', widget);}@@ -185,8 +181,10 @@ async function resetDashboard(id: string) {}async function addDashboardWidget(- widget: Omit<Widget, 'id' | 'x' | 'y' | 'tombstone'> &- Partial<Pick<Widget, 'x' | 'y'>> & { dashboard_page_id: string },+ widget: WithOptional<+ Omit<DashboardWidgetEntity, 'id' | 'tombstone'>,+ 'x' | 'y'+ >,) {// If no x & y was provided - calculate it dynamically// The new widget should be the very last one in the list of all widgets@@ -221,20 +219,20 @@ async function removeDashboardWidget(widgetId: string) {}async function copyDashboardWidget({- widgetId,+ id,targetDashboardPageId,}: {- widgetId: string;+ id: string;targetDashboardPageId: string;}) {// Get the widget to copyconst widget = await db.first<db.DbDashboard>('SELECT * FROM dashboard WHERE id = ? AND tombstone = 0',- [widgetId],+ [id],);if (!widget) {- throw new Error(`Widget not found: ${widgetId}`);+ throw new Error(`Widget not found: ${id}`);}await batchMessages(async () => {@@ -255,18 +253,18 @@ async function copyDashboardWidget({}async function importDashboard({- filepath,+ filePath,dashboardPageId,}: {- filepath: string;+ filePath: string;dashboardPageId: string;}) {try {- if (!(await fs.exists(filepath))) {- throw new Error(`File not found at the provided path: ${filepath}`);+ if (!(await fs.exists(filePath))) {+ throw new Error(`File not found at the provided path: ${filePath}`);}- const content = await fs.readFile(filepath);+ const content = await fs.readFile(filePath);const parsedContent: ExportImportDashboard = JSON.parse(content);exportModel.validate(parsedContent);@@ -337,17 +335,18 @@ async function importDashboard({captureException(err);}if (err instanceof SyntaxError) {- return { error: 'json-parse-error' as const };+ throw new Error('Invalid JSON file.', { cause: 'json-parse-error' });}if (err instanceof ValidationError) {- return { error: 'validation-error' as const, message: err.message };+ throw new Error(err.message, { cause: 'validation-error' });}- return { error: 'internal-error' as const };+ throw new Error('Internal error occurred during import.', {+ cause: 'internal-error',+ });}}export type DashboardHandlers = {- 'dashboard_pages-get': typeof getDashboardPages;'dashboard-create': typeof createDashboardPage;'dashboard-delete': typeof deleteDashboardPage;'dashboard-rename': typeof renameDashboardPage;@@ -362,7 +361,6 @@ export type DashboardHandlers = {export const app = createApp<DashboardHandlers>();-app.method('dashboard_pages-get', getDashboardPages);app.method('dashboard-create', mutator(undoable(createDashboardPage)));app.method('dashboard-delete', mutator(undoable(deleteDashboardPage)));app.method('dashboard-rename', mutator(undoable(renameDashboardPage)));diff --git a/packages/loot-core/src/shared/dashboard.ts b/packages/loot-core/src/shared/dashboard.tsindex f970b4da2e..b3ec2037bc 100644--- a/packages/loot-core/src/shared/dashboard.ts+++ b/packages/loot-core/src/shared/dashboard.ts@@ -1,6 +1,6 @@-import type { NewWidget } from '../types/models';+import type { NewDashboardWidgetEntity } from '../types/models';-export const DEFAULT_DASHBOARD_STATE: NewWidget[] = [+export const DEFAULT_DASHBOARD_STATE: NewDashboardWidgetEntity[] = [// Top row: Key metrics at a glance{type: 'summary-card',diff --git a/packages/loot-core/src/types/models/dashboard.ts b/packages/loot-core/src/types/models/dashboard.tsindex 776dabba20..594f27630a 100644--- a/packages/loot-core/src/types/models/dashboard.ts+++ b/packages/loot-core/src/types/models/dashboard.ts@@ -1,7 +1,7 @@import type { CustomReportEntity } from './reports';import type { RuleConditionEntity } from './rule';-export type DashboardEntity = {+export type DashboardPageEntity = {id: string;name: string;tombstone: boolean;@@ -115,8 +115,11 @@ type SpecializedWidget =| SummaryWidget| CalendarWidget| FormulaWidget;-export type Widget = SpecializedWidget | CustomReportWidget;-export type NewWidget = Omit<Widget, 'id' | 'tombstone' | 'dashboard_page_id'>;+export type DashboardWidgetEntity = SpecializedWidget | CustomReportWidget;+export type NewDashboardWidgetEntity = Omit<+ DashboardWidgetEntity,+ 'id' | 'tombstone' | 'dashboard_page_id'+>;// Exported/imported (json) widget definitionexport type ExportImportCustomReportWidget = Omit<diff --git a/packages/loot-core/src/types/util.ts b/packages/loot-core/src/types/util.tsindex 5af42d9641..cc017263fb 100644--- a/packages/loot-core/src/types/util.ts+++ b/packages/loot-core/src/types/util.ts@@ -10,6 +10,9 @@ export type EverythingButIdOptional<T extends { id: unknown }> = {export type WithRequired<T, K extends keyof T> = T & Required<Pick<T, K>>;+export type WithOptional<T, K extends keyof T> = Omit<T, K> &+ Partial<Pick<T, K>>;+// Allows use of object literals inside child elements of `Trans` tags// see https://github.com/i18next/react-i18next/issues/1483// oxlint-disable-next-line typescript/no-explicit-anydiff --git a/upcoming-release-notes/6957.md b/upcoming-release-notes/6957.mdnew file mode 100644index 0000000000..0ee1dfee0d--- /dev/null+++ b/upcoming-release-notes/6957.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [joel-jeremy]+---++Refactor dashboard data fetching to use React Query for improved performance and maintainability.