Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ (dashboards) ability to save filters & timeframes on spending widgets #3432

Merged
merged 20 commits into from
Sep 24, 2024

Conversation

MatissJanis
Copy link
Member

@MatissJanis MatissJanis commented Sep 13, 2024

Allowing to save spending widgets in dashboards. This required a bit of refactoring to move from LocalPrefs to widgets.

This is a breaking change sadly (i.e. the saved local-pref values will be lost). But IMO that's fine since this is an experimental feature that is expected to have breaking changes.

@actual-github-bot actual-github-bot bot changed the title ✨ (dashboards) ability to save filters & timeframes on spending widgets [WIP] ✨ (dashboards) ability to save filters & timeframes on spending widgets Sep 13, 2024
Copy link

netlify bot commented Sep 13, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit b959cfb
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/66f1ce03c29c2200088732f0
😎 Deploy Preview https://deploy-preview-3432.demo.actualbudget.org
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

github-actions bot commented Sep 13, 2024

Bundle Stats — desktop-client

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
9 5.29 MB → 5.29 MB (+1.15 kB) +0.02%
Changeset
File Δ Size
src/components/reports/reportRanges.ts 📈 +696 B (+20.16%) 3.37 kB → 4.05 kB
src/components/reports/DateRange.tsx 📈 +307 B (+18.67%) 1.61 kB → 1.91 kB
src/components/reports/ReportRouter.tsx 📈 +163 B (+13.24%) 1.2 kB → 1.36 kB
src/components/reports/reports/Spending.tsx 📈 +1.03 kB (+5.78%) 17.8 kB → 18.83 kB
src/components/common/Select.tsx 📈 +48 B (+1.95%) 2.4 kB → 2.45 kB
src/components/reports/graphs/SpendingGraph.tsx 📈 +22 B (+0.27%) 7.91 kB → 7.93 kB
src/components/reports/Overview.tsx 📈 +30 B (+0.19%) 15.68 kB → 15.71 kB
src/components/reports/Header.tsx 📉 -29 B (-0.57%) 4.93 kB → 4.9 kB
src/components/reports/spreadsheets/spending-spreadsheet.ts 📉 -40 B (-0.62%) 6.25 kB → 6.21 kB
src/components/reports/reports/SpendingCard.tsx 📉 -1.05 kB (-19.14%) 5.47 kB → 4.43 kB
View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

Asset File Size % Changed
static/js/ReportRouter.js 1.5 MB → 1.5 MB (+1.1 kB) +0.07%
static/js/index.js 3.31 MB → 3.31 MB (+48 B) +0.00%

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
static/js/indexeddb-main-thread-worker-e59fee74.js 13.5 kB 0%
static/js/resize-observer.js 18.37 kB 0%
static/js/BackgroundImage.js 122.29 kB 0%
static/js/narrow.js 81.24 kB 0%
static/js/usePreviewTransactions.js 1.59 kB 0%
static/js/AppliedFilters.js 20.97 kB 0%
static/js/wide.js 225.27 kB 0%

Copy link
Contributor

github-actions bot commented Sep 13, 2024

Bundle Stats — loot-core

Hey there, this message comes from a GitHub action that helps you and reviewers to understand how these changes affect the size of this project's bundle.

As this PR is updated, I'll keep you updated on how the bundle size is impacted.

Total

Files count Total bundle size % Changed
1 1.19 MB 0%

Changeset

No files were changed

View detailed bundle breakdown

Added

No assets were added

Removed

No assets were removed

Bigger

No assets were bigger

Smaller

No assets were smaller

Unchanged

Asset File Size % Changed
kcab.worker.js 1.19 MB 0%

@MatissJanis MatissJanis changed the title [WIP] ✨ (dashboards) ability to save filters & timeframes on spending widgets ✨ (dashboards) ability to save filters & timeframes on spending widgets Sep 13, 2024
@Teprifer
Copy link

Teprifer commented Sep 14, 2024

  • Opening the graph the month comparison defaulted to April and September with the single month option selected,
    But changing time period then selecting single month set it to September and September.
    Suggest defaulting to Current month vs last month, e.g.

    Compare: $currentMonth
    To: $lastMonth

    Assuming there's data, although your thought to always show a graph even if it's empty to give new users an idea of what they could come back to in the future is fair too.

/ed/ removed incorrect info (see Carkom's comment below)

@carkom
Copy link
Contributor

carkom commented Sep 14, 2024

@Teprifer you are not using the most up-to-date version of edge.

@Teprifer
Copy link

@carkom Doh! I'd updated but not refreshed enough -.- Thanks for the heads up.

@carkom
Copy link
Contributor

carkom commented Sep 15, 2024

Fatal Error found:

  1. Create new spending graph
  2. Open it
  3. Change "To" month to January (or some month with no data)
  4. Click "Budgeted" or "Average" button
  5. Error in SpendingGraph.tsx (w.months[a]] is undefined)

Copy link
Contributor

@carkom carkom left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code looks good. Only suggestion is for a "live" graph option for "single-month". The error I mentioned happens in many situations, so needs to be de-bugged.

options={[
...(reportMode === 'single-month'
? []
: [['current-month', t('Current Month')] as const]),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest we remove the actual current month from the list so it's not duplicated. Could we also offer a "last month" option in the "to" selection and create a "live" graph when "single month" button is chosen?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually removed the notion of "current month" and instead aligned the functionality with the other reports to have a more consistent interface. It did seem like a good idea in the beginning to use the "current month" label, but it actually has a fair few complexities that I hadn't considered. Maybe we will bring it back in a future revision. But for now - no.

--

Added the "live/static" button.

@carkom
Copy link
Contributor

carkom commented Sep 18, 2024

@MatissJanis - the calculateTimeRange is not handling reversed dates. Not sure how it should handle them but current functionality is not very intuitive. I guess just an absolute value for the "month difference"?

  1. use live graph
  2. single-month
  3. compare = August
  4. CompareTo = May
  5. Save
  6. go to reports overview
  7. Notice that the range says December 2024 to September 2024

It's also making the "CompareTo" (which is saved as "end" in the code and the dotted gray line in the graph) equal to the current month which is not the intended function. Current month should be green in a live graph. Seems like the calculateTimeRange is giving you "start" and "end" in reverse order.

Copy link
Contributor

coderabbitai bot commented Sep 18, 2024

Walkthrough

The pull request introduces modifications across several components in the desktop client. Key updates include the addition of a new optional property for customizing popover styling in the Select component, changes to rendering logic in the Header component, and a comprehensive refactor of the Spending component to enhance data handling and user experience. Additionally, the SpendingCard component has been streamlined by removing local preferences and simplifying date range calculations. The reportRanges utility has also been updated for improved flexibility in time range calculations.

Changes

Files Change Summary
packages/desktop-client/src/components/common/Select.tsx Added popoverStyle property to SelectProps for customizing popover styling. Updated popover component to utilize this new prop.
packages/desktop-client/src/components/reports/Header.tsx Modified rendering condition for View component based on path.
packages/desktop-client/src/components/reports/reports/Spending.tsx Refactored to use useParams for fetching widget ID, improved loading state management, and introduced SpendingInternal function for better organization.
packages/desktop-client/src/components/reports/reports/SpendingCard.tsx Refactored to eliminate local preferences, derive spendingReportMode from meta, and simplify date range calculations.
packages/desktop-client/src/components/reports/reportRanges.ts Modified calculateTimeRange function to accept a subset of properties from TimeFrame and enhanced logic for handling date comparisons. Added calculateSpendingReportTimeRange function for improved date range calculations.
packages/desktop-client/src/components/reports/DateRange.tsx Introduced new conditional rendering logic based on the type prop to handle 'budget' and 'average' types distinctly.

Possibly related PRs

  • Update tooltip and themes with better visibility #3298: This PR introduces an additional style property to the SingleAutocomplete component, which is related to enhancing the visual presentation of popovers, similar to the changes made in the main PR that adds a popoverStyle property to the Select component.
  • Fix React Aria Button hover styles  #3453: This PR modifies the Select.tsx file by transitioning from a buttonStyle prop to a more generalized style prop, which aligns with the changes in the main PR that also updates the styling approach in Select.tsx.
  • Fix privacy filter #3472: This PR involves changes to the CellValueText component, which also includes modifications to how styles are applied, similar to the main PR's focus on enhancing the styling mechanism in the Select component.

Suggested labels

✨ Merged


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bf15ce1 and b959cfb.

Files selected for processing (1)
  • packages/desktop-client/src/components/reports/DateRange.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/desktop-client/src/components/reports/DateRange.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Outside diff range and nitpick comments (1)
packages/desktop-client/src/components/reports/reports/Spending.tsx (1)

Line range hint 63-584: Consider breaking down the UI rendering logic into smaller components.

The function is using the useFilters, useReport, useNavigate, and useResponsive hooks for state management, data fetching, navigation, and responsive design, which are good practices. However, the UI rendering logic is quite complex and could be broken down into smaller components for better readability and maintainability.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 183c4b2 and 2b900f6.

Files ignored due to path filters (1)
  • upcoming-release-notes/3432.md is excluded by !**/*.md
Files selected for processing (12)
  • packages/desktop-client/src/components/common/Select.tsx (3 hunks)
  • packages/desktop-client/src/components/reports/DateRange.tsx (1 hunks)
  • packages/desktop-client/src/components/reports/Header.tsx (1 hunks)
  • packages/desktop-client/src/components/reports/Overview.tsx (1 hunks)
  • packages/desktop-client/src/components/reports/ReportRouter.tsx (1 hunks)
  • packages/desktop-client/src/components/reports/graphs/SpendingGraph.tsx (8 hunks)
  • packages/desktop-client/src/components/reports/reports/Spending.tsx (8 hunks)
  • packages/desktop-client/src/components/reports/reports/SpendingCard.tsx (4 hunks)
  • packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts (0 hunks)
  • packages/loot-core/src/types/models/dashboard.d.ts (1 hunks)
  • packages/loot-core/src/types/models/reports.d.ts (0 hunks)
  • packages/loot-core/src/types/prefs.d.ts (0 hunks)
Files not reviewed due to no reviewable changes (3)
  • packages/desktop-client/src/components/reports/spreadsheets/spending-spreadsheet.ts
  • packages/loot-core/src/types/models/reports.d.ts
  • packages/loot-core/src/types/prefs.d.ts
Additional comments not posted (20)
packages/desktop-client/src/components/reports/ReportRouter.tsx (1)

20-20: LGTM! The new route aligns with the PR objective.

The addition of the /spending/:id route with a dynamic :id parameter enables rendering the Spending component for specific spending reports. This change supports the PR objective of allowing users to save individual spending widgets within dashboards, as each saved widget would have a unique identifier.

The implementation looks good and does not appear to negatively impact existing functionality.

packages/desktop-client/src/components/reports/DateRange.tsx (1)

65-70: LGTM!

The new else if block correctly handles the rendering logic for 'budget' and 'average' types. It formats the startDate and displays the appropriate comparison text, enhancing the component's functionality and user experience.

packages/loot-core/src/types/models/dashboard.d.ts (1)

44-50: LGTM! The changes enhance the functionality and versatility of the SpendingWidget.

The addition of the new optional properties (conditions, conditionsOp, timeFrame, and mode) allows for more detailed and customizable representations of spending data:

  • conditions and conditionsOp enable more complex filtering or criteria to be applied to the spending data.
  • timeFrame introduces a temporal aspect to the widget, allowing it to be configured for different periods.
  • mode provides the ability for the widget to operate in different contexts, such as 'single-month', 'budget', or 'average'.

The breaking change is justified given the experimental nature of the feature, as mentioned in the PR objectives. The refactoring effort to transition from LocalPrefs to a widget-based approach seems to be a step towards a more modular and maintainable codebase.

packages/desktop-client/src/components/common/Select.tsx (2)

29-29: LGTM!

The new optional popoverStyle property enhances the flexibility of the Select component by allowing custom styles for the popover. The type CSSProperties is correctly imported and used. This change doesn't introduce any breaking changes or issues.


55-55: LGTM!

The popoverStyle prop is correctly destructured with a default value of an empty object, ensuring that existing code will continue to work without any issues. Applying the popoverStyle prop to the style attribute of the Popover component allows custom styles to be applied when the popover is rendered. These changes are consistent with the addition of the popoverStyle property to the SelectProps type and don't introduce any breaking changes or issues.

Also applies to: 116-116

packages/desktop-client/src/components/reports/reports/SpendingCard.tsx (5)

26-26: LGTM!

The widgetId prop is a valid addition to the SpendingCardProps type.


34-36: LGTM!

The destructuring of the widgetId prop and the default value assignment for the meta prop are valid changes.


40-46: LGTM!

The variable assignments for isDashboardsFeatureEnabled, start, end, and spendingReportMode are valid and consistent with the provided context.


51-59: LGTM!

The variable assignments for selection and getGraphData are valid and consistent with the provided context. The use of useMemo for memoizing the getGraphData function is a good optimization.


Line range hint 63-169: LGTM!

The variable assignments, conditional rendering, and the use of the DateRange, SpendingGraph, and LoadingIndicator components are all valid and consistent with the provided context.

packages/desktop-client/src/components/reports/Header.tsx (1)

76-76: Verify the impact of removing the '/reports/spending' condition.

The change in the conditional rendering logic removes the check for '/reports/spending' path. This means that the View component will now be rendered for any path other than '/reports/custom'.

Please clarify the intention behind this change and verify if it aligns with the expected user interface behavior for different report paths. Ensure that removing the '/reports/spending' condition does not lead to any unintended consequences.

To verify the impact, run the following script:

Verification successful

The removal of '/reports/spending' condition appears intentional and beneficial.

After verifying the codebase, it's clear that the change in Header.tsx allows the View component to be rendered for all report paths except '/reports/custom'. This includes '/reports/spending', '/reports/net-worth', and '/reports/cash-flow'.

The impact of this change is that it simplifies the conditional logic and provides consistent behavior across different report types. It doesn't introduce any issues with existing functionality.

To make the code more explicit and easier to maintain, you might consider using a constant for the excluded path:

const CUSTOM_REPORT_PATH = '/reports/custom';
// ...
{!path.includes(CUSTOM_REPORT_PATH) && (
  // View component
)}

This change enhances readability and allows for easier updates if more paths need to be excluded in the future.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the rendering behavior for different report paths.

# Test: Search for the usage of `'/reports/spending'` path. 
# Expect: Occurrences in other components that might be impacted by this change.
rg --type typescript $'/reports/spending'

# Test: Search for the usage of other report paths (excluding custom and spending).
# Expect: Occurrences of other report paths to verify the rendering behavior.
rg --type typescript $'/reports/(?!custom|spending)\w+'

Length of output: 376


Script:

#!/bin/bash
# Description: Verify the rendering behavior for different report paths.

# Search for the usage of '/reports/spending' path
rg --type ts '/reports/spending'

# Search for the usage of '/reports/custom' path
rg --type ts '/reports/custom'

# Search for other report paths
rg --type ts '/reports/\w+'

# Search for conditional rendering related to report paths
ast-grep --lang typescript --pattern 'path.includes("/reports/")'

# Search for Switch or conditional statements related to report paths
ast-grep --lang typescript --pattern 'switch ($path) { $$$ case "/reports/$_": $$$ }'

Length of output: 3398

packages/desktop-client/src/components/reports/graphs/SpendingGraph.tsx (5)

35-41: LGTM!

The change to the months property in the PayloadItem type provides more flexibility by allowing a dynamic set of month entries. This is a good improvement to the data structure.


48-49: LGTM!

The changes to the balanceTypeOp and selection properties in the CustomTooltipProps type enforce stricter typing. This improves the clarity of the expected values and reduces the risk of incorrect usage. Good job on enhancing the type safety!


65-65: LGTM!

The addition of optional chaining (?.) in several places improves the robustness of the code by safely accessing properties that may not exist in the months object. This prevents potential runtime errors. Nice work on handling the optional properties gracefully!

Also applies to: 88-88, 92-92, 108-108, 112-112


128-128: LGTM!

The change to the mode property in the SpendingGraphProps type enforces stricter typing and improves clarity. The adjustments to the thisMonthMax and selectionMax logic ensure that the code remains robust against undefined values. These changes enhance the type safety and reliability of the code. Well done!

Also applies to: 144-158


161-167: LGTM!

The explicit type definition for the tick formatter enhances type safety for the tick formatting function. This is a good practice to ensure that the function receives and returns the expected types. Nice work on improving the type safety!

packages/desktop-client/src/components/reports/Overview.tsx (1)

548-548: Excellent addition of the widgetId prop to support saving spending widgets!

The widgetId prop, set to the unique identifier item.i, is a crucial change that enables the SpendingCard component to manage its state and settings based on the widget instance. This aligns perfectly with the PR objective of transitioning from LocalPrefs to a widget-based approach for saving spending widgets within dashboards.

packages/desktop-client/src/components/reports/reports/Spending.tsx (3)

45-57: LGTM!

The function is using the useParams hook to retrieve the widget ID from the URL and the useWidget hook to fetch the spending widget data, which are good practices for dynamic routing and data fetching. It also handles the loading state by displaying a LoadingIndicator while the widget data is being fetched, which is a good practice for user experience.


136-157: LGTM!

The onSaveWidget function is saving the widget settings, which is a good practice for user experience.


37-40: Skipping the review of the calculateTimeRange function.

The calculateTimeRange function is imported from an external file and is being used correctly to calculate the start and end dates based on the time frame and mode. Since the function is not defined in this file, it cannot be reviewed in detail.

@MatissJanis
Copy link
Member Author

Thanks @carkom ! This has now been fixed: I aligned the date logic between the spending report and the cashflow/networth reports.

Also sligthly updated the paddings to better align with the other reports.

@carkom
Copy link
Contributor

carkom commented Sep 18, 2024

Thanks @carkom ! This has now been fixed: I aligned the date logic between the spending report and the cashflow/networth reports.

Also sligthly updated the paddings to better align with the other reports.

I'm not sure it works like this. There's a couple issues with aligning to network/cashflow.

  • cashflow/networth are date ranges and this is just 2 separate months so it's not entirely necessary to align them as they are different logic.
  • The "primary" month should be green in the graph. As it is currently, the primary month is gray
  • The displays in the upper right area don't work quite right for current month
  • It's a bit jumpy as you navigate from one mode to the next the code is constantly switching the months around

@carkom
Copy link
Contributor

carkom commented Sep 18, 2024

@MatissJanis
Ultimately the saving part of the UI is error free. The UX could use some polish but I can do that in a later PR if you're fine with that plan. I don't see it as a problem since it's still behind a feature flag.

carkom
carkom previously approved these changes Sep 18, 2024
Copy link
Contributor

@carkom carkom left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code is all good. No fatal errors found in QA testing the UI.

Copy link
Contributor

@carkom carkom left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've left some comments for little nits in the UI function.

There's also a UX bug:

  1. create new graph
  2. switch to budgeted mode
  3. switch to static
  4. choose a month from a couple months back
  5. switch back to live
  6. Save
  7. Navigate to reports homepage and see that the graph is not live
  8. Click on graph to see main graph is also not live

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Outside diff range and nitpick comments (6)
packages/desktop-client/src/components/reports/reports/SpendingCard.tsx (2)

26-28: LGTM: Props updated for widget-based approach

The addition of widgetId and making meta optional align with the PR objectives. These changes support the transition to a widget-based approach.

Consider adding a default value for meta in the prop types to match the default value in the function parameters:

meta?: SpendingWidget['meta'] = {};

This would make the type definition consistent with the function implementation.


40-46: LGTM: Improved state management and time range calculation

The changes align well with the PR objectives:

  1. The new isDashboardsFeatureEnabled flag allows for conditional behavior.
  2. Time range calculation now uses calculateSpendingReportTimeRange, replacing the previous LocalPrefs approach.
  3. spendingReportMode is now derived from the meta prop, simplifying state management.

These updates effectively transition the component to a widget-based approach.

Consider using optional chaining for meta?.mode to make it consistent with other usages of meta in the file:

const spendingReportMode = meta?.mode ?? 'single-month';
packages/desktop-client/src/components/reports/reportRanges.ts (2)

Line range hint 169-194: LGTM! Consider adding a comment for clarity.

The changes to calculateTimeRange look good. The function now handles reversed dates correctly, addressing the issue mentioned in the PR comments. The use of Partial<TimeFrame> also improves flexibility.

Consider adding a brief comment explaining the logic for handling reversed dates (when start > end). This would improve code readability and maintainability. For example:

 if (start > end) {
+  // Handle reversed date range by swapping start and end
   return [
     monthUtils.currentMonth(),
     monthUtils.subMonths(monthUtils.currentMonth(), -offset),
     'sliding-window',
   ] as const;
 }

Line range hint 169-228: Summary: Changes align well with PR objectives

The modifications to calculateTimeRange and the addition of calculateSpendingReportTimeRange effectively address the requirements for saving spending widgets within dashboards. These changes provide the necessary flexibility for handling different reporting scenarios, including reversed date ranges and various modes (budget, average, single-month).

The implementation aligns well with the PR objectives and addresses the issues mentioned in the PR comments, particularly the handling of reversed dates. The transition from using LocalPrefs to a widget-based approach is evident in these changes.

As this feature is still experimental, consider adding comprehensive unit tests to ensure the robustness of these new date handling functions. This will help catch any edge cases and make future refactoring easier as the feature matures.

packages/desktop-client/src/components/reports/reports/Spending.tsx (2)

80-86: Consider refactoring the initialization of compare states

The initialCompare and initialCompareTo variables are used to set the initial state of compare and compareTo, but they are declared after their usage. Consider moving the calculateSpendingReportTimeRange call before the useState calls to improve code clarity.

-  const initialReportMode = widget?.meta?.mode ?? 'single-month';
-  const [initialCompare, initialCompareTo] = calculateSpendingReportTimeRange(
-    widget?.meta ?? {},
-  );
-  const [compare, setCompare] = useState(initialCompare);
-  const [compareTo, setCompareTo] = useState(initialCompareTo);
+  const initialReportMode = widget?.meta?.mode ?? 'single-month';
+  const [initialCompare, initialCompareTo] = calculateSpendingReportTimeRange(
+    widget?.meta ?? {},
+  );
+  const [compare, setCompare] = useState(initialCompare);
+  const [compareTo, setCompareTo] = useState(initialCompareTo);
   const [isLive, setIsLive] = useState(widget?.meta?.isLive ?? true);

Line range hint 1-548: Consider adding comments for complex logic and extracting helper functions

The Spending component has undergone significant improvements in functionality and user experience. To further enhance maintainability, consider:

  1. Adding comments to explain complex logic, especially in the rendering section.
  2. Extracting some of the longer JSX sections into separate components or helper functions to improve readability.
  3. Adding a brief comment at the top of the file explaining the overall purpose and structure of the component.

These minor improvements will help future developers understand and maintain the code more easily.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e1cf74b and bf15ce1.

Files selected for processing (4)
  • packages/desktop-client/src/components/reports/DateRange.tsx (1 hunks)
  • packages/desktop-client/src/components/reports/reportRanges.ts (2 hunks)
  • packages/desktop-client/src/components/reports/reports/Spending.tsx (6 hunks)
  • packages/desktop-client/src/components/reports/reports/SpendingCard.tsx (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/desktop-client/src/components/reports/DateRange.tsx
Additional comments not posted (10)
packages/desktop-client/src/components/reports/reports/SpendingCard.tsx (6)

19-19: LGTM: New import for report time range calculation

The addition of calculateSpendingReportTimeRange import aligns with the PR objective of transitioning to a widget-based approach. This function likely replaces some functionality previously handled by LocalPrefs.


34-36: LGTM: Function parameters updated for widget-based approach

The addition of widgetId parameter and setting a default value for meta are consistent with the updated prop types. These changes support the widget-based approach and ensure the component can work even without meta data.


54-59: LGTM: Graph data calculation updated for widget-based approach

The getGraphData function and its useMemo dependencies have been correctly updated to use properties from the meta object. This change aligns with the transition from LocalPrefs to a widget-based approach.


87-91: LGTM: Conditional routing for dashboard integration

The conditional routing based on isDashboardsFeatureEnabled is a good approach. It allows for seamless integration with the dashboard feature when enabled, while maintaining backwards compatibility. The inclusion of widgetId in the URL when dashboards are enabled supports the new widget-based approach.


169-170: LGTM: Simplified SpendingGraph props

The compare and compareTo props are now directly passed to the SpendingGraph component. This change is consistent with the earlier modifications in time range calculation and simplifies the component's logic.


Line range hint 1-179: Overall: Excellent implementation of widget-based approach

The changes in this file effectively transition the SpendingCard component from using LocalPrefs to a widget-based approach, aligning perfectly with the PR objectives. Key improvements include:

  1. Addition of widgetId for unique widget identification.
  2. Transition to using meta for configuration instead of LocalPrefs.
  3. Improved time range calculation using calculateSpendingReportTimeRange.
  4. Conditional routing to support dashboard integration.
  5. Simplified state management and prop passing.

These changes enhance the component's flexibility and maintainability while preserving backwards compatibility. The code handles the experimental nature of the feature appropriately, using feature flags where necessary.

Great job on implementing these changes! The code is well-structured and effectively addresses the PR objectives.

packages/desktop-client/src/components/reports/reports/Spending.tsx (4)

Line range hint 1-60: Improved component structure and imports

The refactoring of the Spending component into Spending and SpendingInternal improves separation of concerns. The addition of new imports, especially the useWidget hook, suggests better integration with a dashboard feature. This structure will likely enhance maintainability and testability.


61-88: Enhanced state management with widget integration

The use of the useWidget hook and initialization of state variables from widget metadata improves the persistence of user preferences. The addition of isLive and reportMode states provides more flexibility for users.


Line range hint 134-374: Improved user experience with save functionality and live/static toggle

The addition of the onSaveWidget function and related UI elements enhances user experience by allowing persistence of preferences. The live/static toggle provides flexibility in data presentation, and the save button tooltip improves user understanding of the feature.


Line range hint 375-548: Enhanced rendering logic with improved flexibility and analytical capabilities

The updated rendering logic provides more flexibility and customization options for users. The conditional rendering based on widget data improves the component's adaptability, and the support for different report modes (single-month, budget, average) enhances the analytical capabilities of the component. These changes significantly improve the overall functionality and user experience of the Spending report.

@MatissJanis
Copy link
Member Author

Thanks for such diligent testing @carkom ! Should be patched now.

Copy link
Contributor

@carkom carkom left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks for putting up with all the nits. Cheers!

@MatissJanis MatissJanis merged commit f3451bf into master Sep 24, 2024
20 checks passed
@MatissJanis MatissJanis deleted the matiss/dashboard-spending branch September 24, 2024 07:03
a-gradina pushed a commit to a-gradina/actual that referenced this pull request Sep 24, 2024
matt-fidd added a commit that referenced this pull request Oct 3, 2024
* marked files for translation

* added release note

* fixed linting warnings

* 🐛 fix account filters being overridden (#3441)

* :electron: Reduce package size  (#3443)

* reduce package size of all packages

* release notes

* Update beforePackHook.ts

* [Maintenance] Cleanup react aria packages and dedupe (#3450)

* Cleanup react aria packages and dedupe

* Release notes

* ♻️ (synced-prefs) moving the prefs from metadata.json to the db (#3423)

* :electron: Restart server silently when adding self signed cert and add some logs (#3431)

* restart server silently on add self signed cert and add some logging

* release notes

* fix name

* updating names to be more specific

* removing setloading

* feedback

* ♻️ (synced-prefs) move budget type to synced prefs (#3427)

* update synced account balance in db if available (#3452)

* 🐛 (synced-prefs) fix bulk-reading not working in import modal (#3460)

* fix: csv import deduplication (#3456)

* ✨ release simplefin as a first-party feature (#3459)

Closes #2272

* Do not allow renaming to an empty category or group name (#3463)

* Do not allow renaming to an emoty category or group name

* Release notes

* [Mobile] Fix #3214 - Pull down to refresh triggering clicks on budget cells (#3374)

* Fix #3214

* Fix rollover indicator

* VRT

* Fix typecheck error

* VRT

* Release notes

* VRT

* Update style

* Fix budgeted

* VRT

* VRT

* Revert VRT

* VRT

* Fix style

* Revert usePreviewTransactions

* Fix error

* Fix reports form submit handlers (#3462)

* Fix form submit handlers

* Release notes

* :electron: Remove some old updater code (#3468)

* remove some old updater code

* remove old updater logic

* CSV import e2e tests (#3467)

* Fix React Aria Button hover styles  (#3453)

* Fiox hover styles and use className instead of inline to prepare for future css migration

* Release notes

* Cleanup

* Update edit rule hover style

* Undoable auto transfer notes + auto notes for cover (#3411)

* Undo auto transfer notes + auto notes for cover

* Release notes

* Fix notes

* Fix notes undo

* Do not show clicked category on transfer or cover menus

* Fix typecheck error

* typecheck

* Fix removeCategoriesFromGroups

* 🐛 (reports) deleting custom report should remove it from the dashboard (#3469)

* Revert "CSV import e2e tests (#3467)" (#3474)

This reverts commit 5e12d40.

* ♻️ (synced-prefs) separate metadata and local prefs out (#3458)

* :electron: Replace deprecated file protocol registration (#3475)

* replace deprecated file handler in electron

* release notes

* types eh

* types

* update sql regexp to default to empty string when field is null (#3480)

* ♻️ rename report/rollover budget to tracking/envelope (#3483)

* 🐛 (import) fix csv import checkboxes not working (#3478)

* Update tooltip and themes with better visibility (#3298)

* Update tooltip and themes with better visibility

* Rename merge request # into release notes

* rename release note

* update VRT

* tweak light theme

* dont put border on autocomplete menus

* update VRT

* tweak popover style

* simplify

* update VRT

* update VRT

---------

Co-authored-by: Dustin Conlon <[email protected]>
Co-authored-by: Dustin Conlon <[email protected]>
Co-authored-by: youngcw <[email protected]>

* fix modals on mobile BudgetTable (#3487)

* Fix privacy filter (#3472)

* Fix privacy filter

* Release notes

* Coderabbit suggestion

* VRT

* VRT

* Revert VRT

* VRT

* VRT

* VRT

* VRT

* Delete VRT

* VRT

* Revert VRT

* 🐛 fix custom reports crashing when opening table (#3484)

* 🧪 (tests) adding custom report e2e tests (#3493)

* ✨ (dashboards) ability to save filters & timeframes on spending widgets (#3432)

* marked files for translation

* Revert ":bug: fix account filters being overridden (#3441)"

This reverts commit 7336bad.

* Revert "Revert ":bug: fix account filters being overridden (#3441)""

This reverts commit 5cbadc4.

* Revert changes due to failed rebase

* removed import of t

* fixed lint warning

* added PayeeTableRow.tsx

* needed changes

* bugfix: pluralization

* variables adjustments

* removed doubled trans

---------

Co-authored-by: Matiss Janis Aboltins <[email protected]>
Co-authored-by: Michael Clark <[email protected]>
Co-authored-by: Joel Jeremy Marquez <[email protected]>
Co-authored-by: Matt Fiddaman <[email protected]>
Co-authored-by: Koen van Staveren <[email protected]>
Co-authored-by: Ryan Bianchi <[email protected]>
Co-authored-by: Robert Dyer <[email protected]>
Co-authored-by: Dustin Conlon <[email protected]>
Co-authored-by: Dustin Conlon <[email protected]>
Co-authored-by: youngcw <[email protected]>
Co-authored-by: Tim <[email protected]>
@coderabbitai coderabbitai bot mentioned this pull request Nov 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: Monthly spending report - Renderer Issues
5 participants