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

Add YTD and last year to Reports headers #4019

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

rodriguestiago0
Copy link
Contributor

@rodriguestiago0 rodriguestiago0 commented Dec 21, 2024

Add "Year to date" and "Last year" to header report

image

@actual-github-bot actual-github-bot bot changed the title Add YTD and last year to Reports headers [WIP] Add YTD and last year to Reports headers Dec 21, 2024
Copy link

netlify bot commented Dec 21, 2024

Deploy Preview for actualbudget ready!

Name Link
🔨 Latest commit 690627e
🔍 Latest deploy log https://app.netlify.com/sites/actualbudget/deploys/67687df7ac8b96000932836e
😎 Deploy Preview https://deploy-preview-4019.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 Dec 21, 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
10 5.53 MB → 5.53 MB (+1.8 kB) +0.03%
Changeset
File Δ Size
node_modules/es-define-property/index.js 📈 +210 B (+60.00%) 350 B → 560 B
src/components/reports/Header.tsx 📈 +767 B (+15.68%) 4.78 kB → 5.53 kB
src/components/reports/reports/NetWorth.tsx 📈 +240 B (+3.79%) 6.18 kB → 6.42 kB
src/components/reports/reports/CashFlow.tsx 📈 +240 B (+2.62%) 8.96 kB → 9.19 kB
node_modules/has-property-descriptors/index.js 📈 +9 B (+1.57%) 573 B → 582 B
src/components/reports/reports/Summary.tsx 📈 +240 B (+1.51%) 15.53 kB → 15.76 kB
node_modules/call-bind/index.js 📈 +9 B (+0.85%) 1.04 kB → 1.05 kB
src/components/reports/reports/Calendar.tsx 📈 +122 B (+0.46%) 26.11 kB → 26.23 kB
node_modules/define-data-property/index.js 📈 +9 B (+0.39%) 2.24 kB → 2.25 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.58 MB → 1.58 MB (+1.57 kB) +0.10%
static/js/index.js 3.45 MB → 3.45 MB (+237 B) +0.01%

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/workbox-window.prod.es5.js 5.69 kB 0%
static/js/narrow.js 83.36 kB 0%
static/js/wide.js 161.25 kB 0%
static/js/useAccountPreviewTransactions.js 1.63 kB 0%
static/js/TransactionList.js 102.91 kB 0%

Copy link
Contributor

github-actions bot commented Dec 21, 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.32 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.32 MB 0%

@youngcw
Copy link
Member

youngcw commented Dec 21, 2024

The end date selector doesn't get a date added in when using the new buttons. That will need fixed.

@rodriguestiago0
Copy link
Contributor Author

The end date selector doesn't get a date added in when using the new buttons. That will need fixed.

Done

@rodriguestiago0 rodriguestiago0 changed the title [WIP] Add YTD and last year to Reports headers Add YTD and last year to Reports headers Dec 22, 2024
Copy link
Contributor

coderabbitai bot commented Dec 22, 2024

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/desktop-client/src/components/reports/Header.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-eslint-plugin".

(The package "eslint-plugin-eslint-plugin" was not found when loaded as a Node module from the directory "/packages/eslint-plugin-actual".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-eslint-plugin@latest --save-dev

The plugin "eslint-plugin-eslint-plugin" was referenced from the config file in "packages/eslint-plugin-actual/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

The pull request introduces a series of modifications across multiple report components in the desktop client, focusing on enhancing date-related functionalities. The changes primarily involve adding two new props to the Header component: earliestTransaction (a string representing the earliest transaction date) and firstDayOfWeekIdx (an optional index for the first day of the week).

The modifications are consistently applied across several report components, including Calendar, CashFlow, NetWorth, and Summary. In each component, a new state variable earliestTransaction is introduced, typically initialized as an empty string. Additionally, the firstDayOfWeekIdx is retrieved using the useSyncedPref hook, with a default value of '0' if no preference is set.

The Header component in Header.tsx is updated to accept these new props, and a new convertToMonth function is added to handle date range conversions. The changes enable more flexible date range selection, particularly with the addition of "Year to date" and "Last year" buttons that utilize the getLiveRange function with the new parameters.

Possibly related PRs

Suggested labels

sparkles: Merged

Suggested reviewers

  • youngcw
  • MikesGlitch

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 3

🧹 Nitpick comments (3)
packages/desktop-client/src/components/reports/Header.tsx (1)

34-35: Props type declarations need documentation.

The newly added props lack TypeScript documentation explaining their purpose and expected format.

Add JSDoc comments to document the props:

 type HeaderProps = {
+  /** ISO date string of the earliest transaction in the system */
   earliestTransaction: string;
+  /** Index of the first day of the week (0-6, where 0 is Sunday) */
   firstDayOfWeekIdx?: SyncedPrefs['firstDayOfWeekIdx'];
packages/desktop-client/src/components/reports/reports/NetWorth.tsx (1)

166-168: Remove unused state setter and improve variable naming.

  1. The state setter _ is unused and can be removed
  2. The variable name _firstDayOfWeekIdx is unclear

Apply these improvements:

-const [earliestTransaction, _] = useState('');
+const [earliestTransaction] = useState('');
-const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');
-const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';
+const [syncedFirstDayOfWeek] = useSyncedPref('firstDayOfWeekIdx');
+const firstDayOfWeekIdx = syncedFirstDayOfWeek || '0';
packages/desktop-client/src/components/reports/reports/Calendar.tsx (1)

Line range hint 151-153: Consider creating a custom hook for transaction date management

The pattern of managing earliestTransaction and firstDayOfWeekIdx is repeated across components. Consider extracting this logic into a custom hook for better code reuse.

Example implementation:

// hooks/useTransactionDateManagement.ts
export function useTransactionDateManagement() {
  const [earliestTransaction, setEarliestTransaction] = useState('');
  const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');
  const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';

  useEffect(() => {
    async function fetchEarliestTransaction() {
      try {
        const trans = await send('get-earliest-transaction');
        if (trans) {
          setEarliestTransaction(trans.date);
        }
      } catch (error) {
        console.error('Error fetching earliest transaction:', error);
      }
    }
    fetchEarliestTransaction();
  }, []);

  return { earliestTransaction, firstDayOfWeekIdx };
}

Also applies to: 463-464

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6cfb9d2 and 121d09b.

⛔ Files ignored due to path filters (1)
  • upcoming-release-notes/4019.md is excluded by !**/*.md
📒 Files selected for processing (5)
  • packages/desktop-client/src/components/reports/Header.tsx (6 hunks)
  • packages/desktop-client/src/components/reports/reports/Calendar.tsx (2 hunks)
  • packages/desktop-client/src/components/reports/reports/CashFlow.tsx (3 hunks)
  • packages/desktop-client/src/components/reports/reports/NetWorth.tsx (3 hunks)
  • packages/desktop-client/src/components/reports/reports/Summary.tsx (3 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/desktop-client/src/components/reports/reports/Summary.tsx (1)
Learnt from: lelemm
PR: actualbudget/actual#3792
File: packages/desktop-client/src/components/reports/reports/Summary.tsx:134-161
Timestamp: 2024-11-12T19:52:52.889Z
Learning: In `packages/desktop-client/src/components/reports/reports/Summary.tsx`, API calls like `get-earliest-transaction` are used without explicit error handling to maintain consistency with other components.
🔇 Additional comments (5)
packages/desktop-client/src/components/reports/Header.tsx (1)

173-206: Verify error handling in the new date range buttons.

The implementation assumes getLiveRange always returns valid dates, but there's no error handling if it fails.

Also, consider adding error boundaries to handle potential failures gracefully.

Add error handling:

 <Button
   variant="bare"
   onPress={() =>
-    onChangeDates(
-      ...convertToMonth(
-        ...getLiveRange(
-          'Year to date',
-          earliestTransaction,
-          true,
-          firstDayOfWeekIdx,
-        ),
-      ),
-    )
+    try {
+      const range = getLiveRange(
+        'Year to date',
+        earliestTransaction,
+        true,
+        firstDayOfWeekIdx,
+      );
+      onChangeDates(...convertToMonth(...range));
+    } catch (error) {
+      console.error('Failed to get date range:', error);
+      // Handle error appropriately
+    }
   }
 >
packages/desktop-client/src/components/reports/reports/CashFlow.tsx (2)

191-193: Same issues as in NetWorth component.

The implementation has the same issues regarding unused state setter and unclear variable naming.

Please apply the same improvements suggested for the NetWorth component:

  1. Remove unused state setter
  2. Improve variable naming clarity

232-233: 🛠️ Refactor suggestion

Consider initializing earliestTransaction.

The earliestTransaction is passed to Header while being initialized as an empty string, which might cause issues with the new date range buttons.

Consider initializing it with a proper value:

-const [earliestTransaction, _] = useState('');
+const [earliestTransaction] = useState(() => {
+  // Initialize with current date or fetch from API
+  return new Date().toISOString().split('T')[0];
+});
packages/desktop-client/src/components/reports/reports/Summary.tsx (1)

281-282: LGTM: Props correctly passed to Header component

The new props earliestTransaction and firstDayOfWeekIdx are properly passed to the Header component.

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

497-498: LGTM: Props correctly passed to Header component

The new props earliestTransaction and firstDayOfWeekIdx are properly passed to the Header component, maintaining consistency with other components.

Comment on lines +72 to +78
function convertToMonth(
start: string,
end: string,
mode: TimeFrame['mode'],
): [string, string, TimeFrame['mode']] {
return [monthUtils.getMonth(start), monthUtils.getMonth(end), mode];
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding input validation to convertToMonth.

The function assumes valid date strings but doesn't handle invalid inputs.

Add input validation:

 function convertToMonth(
   start: string,
   end: string,
   mode: TimeFrame['mode'],
 ): [string, string, TimeFrame['mode']] {
+  if (!start || !end) {
+    throw new Error('Invalid date strings provided');
+  }
   return [monthUtils.getMonth(start), monthUtils.getMonth(end), mode];
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function convertToMonth(
start: string,
end: string,
mode: TimeFrame['mode'],
): [string, string, TimeFrame['mode']] {
return [monthUtils.getMonth(start), monthUtils.getMonth(end), mode];
}
function convertToMonth(
start: string,
end: string,
mode: TimeFrame['mode'],
): [string, string, TimeFrame['mode']] {
if (!start || !end) {
throw new Error('Invalid date strings provided');
}
return [monthUtils.getMonth(start), monthUtils.getMonth(end), mode];
}

Comment on lines +151 to +153
const [earliestTransaction, _] = useState('');
const [_firstDayOfWeekIdx] = useSyncedPref('firstDayOfWeekIdx');
const firstDayOfWeekIdx = _firstDayOfWeekIdx || '0';
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Initialize earliestTransaction state with data from useEffect

The earliestTransaction state is initialized but never updated, despite having an effect that fetches the earliest transaction. Consider updating the state within the effect.

- const [earliestTransaction, _] = useState('');
+ const [earliestTransaction, setEarliestTransaction] = useState('');

  useEffect(() => {
    async function run() {
      const trans = await send('get-earliest-transaction');
+     if (trans) {
+       setEarliestTransaction(trans.date);
+     }
      // ... rest of the effect
    }
    run();
  }, []);

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +463 to +464
const [earliestTransaction, _] = useState('');

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Initialize earliestTransaction state with data from useEffect

The earliestTransaction state is initialized but never updated. The component already has an effect that fetches the earliest transaction, which should be used to update this state.

- const [earliestTransaction, _] = useState('');
+ const [earliestTransaction, setEarliestTransaction] = useState('');

  useEffect(() => {
    async function run() {
      try {
        const trans = await send('get-earliest-transaction');
+       if (trans) {
+         setEarliestTransaction(trans.date);
+       }
        // ... rest of the effect
      } catch (error) {
        console.error('Error fetching earliest transaction:', error);
      }
    }
    run();
  }, []);

Committable suggestion skipped: line range outside the PR's diff.

@youngcw
Copy link
Member

youngcw commented Dec 22, 2024

/update-vrt

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.

2 participants