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

feat(income-plan): Use new temporary income plan calculation data #16933

Merged
merged 8 commits into from
Nov 25, 2024

Conversation

helgifr
Copy link
Member

@helgifr helgifr commented Nov 19, 2024

Use new temporary income plan calculation data

What

Specify what you're trying to achieve

Why

Specify why you need to achieve this

Screenshots / Gifs

Attach Screenshots / Gifs to help reviewers understand the scope of the pull request

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a PrintScreen component for easy printing of income plan details.
    • Enhanced IncomePlanForm with new fields for month selection and print overview.
  • Improvements

    • Updated TemporaryCalculationTable for better accuracy in displaying monthly amounts.
    • Improved localization messages for clearer guidance on income plans.
  • Bug Fixes

    • Streamlined data handling for improved user experience during data fetching.

@helgifr helgifr requested a review from a team as a code owner November 19, 2024 09:59
Copy link
Contributor

coderabbitai bot commented Nov 19, 2024

Walkthrough

This pull request introduces a new PrintScreen React component and modifies existing components within the income plan module. The PrintScreen component allows users to trigger the browser's print functionality. The TemporaryCalculationTable component has been updated to improve its data handling and display, while the IncomePlanForm has been enhanced with new fields and imports. Additionally, localization messages have been updated to reflect changes in the application's user interface.

Changes

File Change Summary
libs/application/templates/social-insurance-administration/income-plan/src/fields/PrintScreen/index.tsx Added new PrintScreen component to trigger print functionality.
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx Updated imports and logic for rendering table headers; removed print button; adjusted data handling.
libs/application/templates/social-insurance-administration/income-plan/src/fields/index.ts Added export for the new PrintScreen component.
libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts Enhanced form structure with new fields and imports, including temporaryCalculation and overviewPrint.
libs/application/templates/social-insurance-administration/income-plan/src/lib/incomePlanUtils.ts Updated getApplicationAnswers function to include temporaryCalculationMonth.
libs/application/templates/social-insurance-administration/income-plan/src/lib/messages.ts Renamed and added localization message identifiers for improved clarity in the application.

Possibly related PRs

Suggested labels

deploy-feature

Suggested reviewers

  • kksteini
  • birkirkristmunds

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.

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

codecov bot commented Nov 19, 2024

Codecov Report

Attention: Patch coverage is 0% with 3 lines in your changes missing coverage. Please review.

Project coverage is 35.83%. Comparing base (38c1469) to head (9e7daff).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...inistration/income-plan/src/lib/incomePlanUtils.ts 0.00% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16933      +/-   ##
==========================================
+ Coverage   35.59%   35.83%   +0.23%     
==========================================
  Files        6924     6910      -14     
  Lines      146340   145925     -415     
  Branches    41553    41662     +109     
==========================================
+ Hits        52096    52286     +190     
+ Misses      94244    93639     -605     
Flag Coverage Δ
api 3.34% <ø> (ø)
application-system-api 38.74% <0.00%> (+<0.01%) ⬆️
application-template-api-modules 27.72% <0.00%> (-0.02%) ⬇️
application-ui-shell 20.55% <ø> (ø)
web 1.74% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...nce-administration/income-plan/src/lib/messages.ts 100.00% <ø> (ø)
...inistration/income-plan/src/lib/incomePlanUtils.ts 18.86% <0.00%> (-0.74%) ⬇️

... and 65 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 38c1469...9e7daff. Read the comment docs.

---- 🚨 Try these New Features:

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 19, 2024

Datadog Report

All test runs f96d900 🔗

5 Total Test Services: 0 Failed, 5 Passed
🔻 Test Sessions change in coverage: 1 decreased (-1.38%), 8 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.44s 1 no change Link
application-system-api 0 0 0 40 0 2m 8.28s 1 no change Link
application-template-api-modules 0 0 0 116 0 2m 7.34s 1 no change Link
application-ui-shell 0 0 0 74 0 30.95s 1 no change Link
web 0 0 0 84 0 31.11s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • application-templates-social-insurance-administration-income-plan - jest 29.92% (-1.38%) - Details

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: 8

🧹 Outside diff range and nitpick comments (8)
libs/application/templates/social-insurance-administration/income-plan/src/fields/PrintScreen/index.tsx (1)

3-16: Improve component reusability with props

The component could be more reusable by accepting props for customization.

-export const PrintScreen: FC = () => {
+interface PrintScreenProps {
+  buttonVariant?: 'utility' | 'primary' | 'secondary'
+  className?: string
+  onPrintStart?: () => void
+  onPrintError?: (error: unknown) => void
+}
+
+export const PrintScreen: FC<PrintScreenProps> = ({
+  buttonVariant = 'utility',
+  className,
+  onPrintStart,
+  onPrintError,
+}) => {
   return (
-    <Box display="flex" justifyContent="flex-end">
+    <Box display="flex" justifyContent="flex-end" className={className}>
       <Button
-        variant="utility"
+        variant={buttonVariant}
         icon="print"
         aria-label="Print page"
         onClick={(e) => {
           e.preventDefault()
+          onPrintStart?.()
           try {
             window.print()
           } catch (error) {
-            console.error('Failed to initiate printing:', error)
+            onPrintError?.(error)
           }
         }}
       />
libs/application/templates/social-insurance-administration/income-plan/src/lib/incomePlanUtils.ts (2)

83-91: Consider adding a default value for temporaryCalculationMonth

The code looks good, but consider providing a default value for temporaryCalculationMonth to handle cases where the path doesn't exist.

  const temporaryCalculationMonth = getValueViaPath(
    answers,
    'temporaryCalculation.month',
-  ) as string
+  ) as string ?? ''

83-91: Add explicit return type annotation

To improve maintainability and make the contract clearer, consider adding an explicit return type annotation to the function.

- export const getApplicationAnswers = (answers: Application['answers']) => {
+ export const getApplicationAnswers = (answers: Application['answers']): {
+   incomePlan: IncomePlanRow[];
+   temporaryCalculationMonth: string;
+ } => {
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (2)

164-178: Improve month selection fallback behavior

The current fallback to MONTHS[0].label when no month is selected could lead to misleading information.

Consider handling the undefined case more explicitly:

-                    MONTHS.find(
-                      ({ value }) => value === temporaryCalculationMonth,
-                    )?.label ?? MONTHS[0].label,
+                    temporaryCalculationMonth
+                      ? MONTHS.find(({ value }) => value === temporaryCalculationMonth)?.label
+                      : formatMessage(incomePlanFormMessage.info.selectMonth),

226-230: Improve empty header cell accessibility and style

The empty header cell should be marked as hidden for screen readers, and the style could be more concise.

-                <T.HeadData
-                  width="25%"
-                  align="right"
-                  box={{ paddingRight: 0 }}
-                ></T.HeadData>
+                <T.HeadData width="25%" align="right" box={{ paddingRight: 0 }} aria-hidden="true" />
libs/application/templates/social-insurance-administration/income-plan/src/lib/messages.ts (2)

Line range hint 1-2: Enhance type safety with a more specific MessageDir type

The current MessageDir type could be more specific to better represent the actual structure of the messages object.

Consider this improvement:

-type MessageDir = Record<string, Record<string, MessageDescriptor>>
+type MessageSection = 'shared' | 'pre' | 'info' | 'incomePlan' | 'confirm' | 'conclusionScreen'
+type MessageDir = Record<MessageSection, Record<string, MessageDescriptor>>

Line range hint 106-114: Complete the English translation in the assumptions message description

The description field contains an incomplete English translation: 'Calculations of tax payments are based on the following assumptions: \n*Transl'

Consider completing the translation to match the defaultMessage content:

-      description:
-        'Calculations of tax payments are based on the following assumptions: \n*Transl',
+      description:
+        'Calculations of tax payments are based on the following assumptions: \n* As a general rule, payments from the Social Insurance Administration are placed in the lowest possible tax bracket based on the income plan. You can request a change in tax bracket on TR\'s website. \n* Personal allowance is based on 100% utilization of the tax card',
libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (1)

636-642: Improve type safety for the month selection field.

The month selection configuration could be enhanced for better type safety and maintainability.

Consider these improvements:

 buildSelectField({
   id: 'temporaryCalculation.month',
   title: socialInsuranceAdministrationMessage.period.month,
   width: 'half',
   options: MONTHS,
-  defaultValue: 'January',
+  defaultValue: MONTHS[0].value,
+  validate: (value) => MONTHS.some((month) => month.value === value) || 'Invalid month',
 }),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b3e05fd and 921f672.

📒 Files selected for processing (6)
  • libs/application/templates/social-insurance-administration/income-plan/src/fields/PrintScreen/index.tsx (1 hunks)
  • libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (5 hunks)
  • libs/application/templates/social-insurance-administration/income-plan/src/fields/index.ts (1 hunks)
  • libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (3 hunks)
  • libs/application/templates/social-insurance-administration/income-plan/src/lib/incomePlanUtils.ts (1 hunks)
  • libs/application/templates/social-insurance-administration/income-plan/src/lib/messages.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
libs/application/templates/social-insurance-administration/income-plan/src/fields/PrintScreen/index.tsx (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/social-insurance-administration/income-plan/src/fields/index.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/social-insurance-administration/income-plan/src/lib/incomePlanUtils.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/social-insurance-administration/income-plan/src/lib/messages.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (5)
libs/application/templates/social-insurance-administration/income-plan/src/fields/PrintScreen/index.tsx (1)

1-18: Verify form field integration

Let's verify how this component is integrated into the form system as mentioned in the summary.

✅ Verification successful

Component integration is properly configured

The PrintScreen component is correctly integrated into the form system:

  • It's properly exported from fields/index.ts for form usage
  • It's referenced in IncomePlanForm.ts as a form component
  • The implementation is a standalone UI component that doesn't require form field integration since it's just a print button
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for PrintScreen usage in form configurations
rg -l "PrintScreen" "libs/application/templates/social-insurance-administration/income-plan/src/"

# Search for specific field configuration
ast-grep --pattern 'overviewPrint = {
  $$$
  component: $PrintScreen,
  $$$
}'

Length of output: 471


Script:

#!/bin/bash
# Let's check how PrintScreen is used in the form configuration
rg -A 10 "PrintScreen" "libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts"

# Check how it's exported in fields/index.ts
cat "libs/application/templates/social-insurance-administration/income-plan/src/fields/index.ts"

Length of output: 768

libs/application/templates/social-insurance-administration/income-plan/src/lib/messages.ts (2)

101-110: LGTM! Clear and descriptive message identifiers

The new message identifiers are more semantic and the dynamic year placeholder in tableHeaderTotal improves reusability.


Line range hint 1-576: LGTM! Well-organized and reusable message structure

The messages are:

  • Organized in logical sections
  • Properly namespaced with unique IDs
  • Well-documented with English descriptions
    This structure promotes reusability across different NextJS apps.
libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (2)

7-7: LGTM! Well-organized imports from core modules.

The new imports are correctly sourced from shared core modules, maintaining good reusability practices across NextJS applications.

Also applies to: 41-41


Line range hint 584-591: Verify error handling for external data.

The section's visibility depends on latestIncomePlan from external data. Consider adding error handling for malformed data.

✅ Verification successful

Let me analyze the usage of getApplicationExternalData to understand how external data is handled. I'll check for error handling patterns.


External data handling is properly implemented

The code already has appropriate error handling for latestIncomePlan:

  1. It uses isEmpty() checks before accessing the data
  2. The visibility condition is controlled by !isEmpty(latestIncomePlan)
  3. The UI message is conditionally rendered based on hasLatestIncomePlan

These patterns demonstrate that malformed data is handled gracefully through null checks and conditional rendering.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for error handling in external data usage
rg -A 5 "getApplicationExternalData" --type ts

Length of output: 216816


Script:

#!/bin/bash
# Check for error handling patterns around latestIncomePlan
ast-grep --pattern 'const { latestIncomePlan } = getApplicationExternalData($$$)'

# Check for isEmpty usage with latestIncomePlan
rg -A 3 "isEmpty\(latestIncomePlan\)" --type ts

Length of output: 1877

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)
libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (1)

636-642: Add TypeScript interface for form data structure.

To improve type safety and maintainability, consider adding an interface for the form's data structure, especially for the temporaryCalculation section.

interface TemporaryCalculationData {
  month: string;
  // Add other fields as needed
}

interface IncomePlanFormData {
  temporaryCalculation: TemporaryCalculationData;
  // Add other form sections
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 921f672 and 9b8432f.

📒 Files selected for processing (1)
  • libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (2)
libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (2)

7-7: LGTM! Import changes are well-organized.

The new imports are properly grouped and sourced from internal packages, promoting code reusability across the application.

Also applies to: 41-41


636-642: Verify month selector's default value initialization.

While setting the default value to the current month is logical, ensure that the MONTHS array has the expected length (12) to prevent potential array index out of bounds issues.

✅ Verification successful

Based on the shell script results, I can now generate the final response since I have sufficient information about the MONTHS constant and its usage:

Month selector's default value initialization is safe and properly structured.

The MONTHS constant in libs/application/templates/social-insurance-administration/core/src/lib/constants.ts is correctly defined as an array of 12 month objects, each containing a value and label property. The default value access using MONTHS[new Date().getMonth()] is safe since:

  • The array has exactly 12 elements matching JavaScript's getMonth() range (0-11)
  • Each element has the required value property that's being accessed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify MONTHS constant definition and usage
# Expected: MONTHS should be an array of 12 month options

# Search for MONTHS constant definition
ast-grep --pattern 'const MONTHS = $_'

# Search for other usages of MONTHS to ensure consistent structure
rg 'MONTHS\[' -A 2

Length of output: 8355

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 (3)
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (3)

160-162: Extract complex data access logic to a utility function

The nested optional chaining and multiple conditions make the code harder to maintain and understand.

Consider extracting this logic to a utility function:

const getPaidOutMonths = (data?: { getTemporaryCalculations?: SocialInsuranceTemporaryCalculation }) => {
  return data?.getTemporaryCalculations?.groups
    ?.find(({ group }) => group === 'Frádráttur')
    ?.rows?.find(({ name }) => name === 'Útborgað')?.months;
};

178-182: Simplify month label selection logic

The nested optional chaining with fallback can be simplified using nullish coalescing.

-  {formatMessage(
-    MONTHS.find(
-      ({ value }) => value === temporaryCalculationMonth,
-    )?.label ?? MONTHS[0].label,
-  )}
+  {formatMessage(
+    MONTHS.find(({ value }) => value === temporaryCalculationMonth)?.label 
+    ?? formatMessage(incomePlanFormMessage.info.defaultMonth)
+  )}

Line range hint 192-227: Extract table group rendering to a separate component

The nested mapping and conditional rendering logic would be more maintainable as a separate component.

Consider creating a CalculationTableGroup component:

interface CalculationTableGroupProps {
  group: typeof data.getTemporaryCalculations.groups[0];
  monthIndex: number;
}

const CalculationTableGroup: FC<CalculationTableGroupProps> = ({ group, monthIndex }) => {
  return (
    <T.Table>
      <T.Head>{/* ... */}</T.Head>
      <T.Body>{/* ... */}</T.Body>
    </T.Table>
  );
};
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9b8432f and fd128f8.

📒 Files selected for processing (3)
  • libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (5 hunks)
  • libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (3 hunks)
  • libs/application/templates/social-insurance-administration/income-plan/src/lib/incomePlanUtils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/application/templates/social-insurance-administration/income-plan/src/lib/incomePlanUtils.ts
🧰 Additional context used
📓 Path-based instructions (2)
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (4)
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (1)

91-93: LGTM! Good type safety improvement

The explicit type definition for the query response enhances type safety and maintainability.

libs/application/templates/social-insurance-administration/income-plan/src/forms/IncomePlanForm.ts (3)

7-7: LGTM! Import changes follow best practices.

The new imports maintain good tree-shaking practices by importing specific entities and leverage core packages for reusability.

Also applies to: 42-42


631-636: Skip comment about PrintScreen component types.

A previous review already covered the need for TypeScript type definitions for the PrintScreen component.


637-645: Consider server-side default month value.

The default month value is set using client-side new Date(). This could cause inconsistencies if the server and client times differ. Consider:

  1. Passing the current month from the server
  2. Using a consistent timezone for date calculations
-              defaultValue: MONTHS[new Date().getMonth()].value,
+              defaultValue: (application) => {
+                const { serverTime } = getApplicationExternalData(application.externalData)
+                return MONTHS[new Date(serverTime).getMonth()].value
+              },

Copy link
Member

@ylfahfa ylfahfa left a comment

Choose a reason for hiding this comment

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

lgtm 🏆

@helgifr helgifr added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 25, 2024
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: 2

🧹 Outside diff range and nitpick comments (3)
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (3)

22-24: Consider reorganizing imports for better tree-shaking

Group imports by their source:

  1. External dependencies (react-hook-form)
  2. Internal shared dependencies (constants, schema)
  3. Local imports
+import { useFormContext } from 'react-hook-form'
+
 import { SocialInsuranceTemporaryCalculation } from '../../types/schema'
 import { MONTHS } from '@island.is/application/templates/social-insurance-administration-core/lib/constants'
-import { useFormContext } from 'react-hook-form'

92-94: Enhance type safety for GraphQL query

Define a dedicated type for the query response to improve type safety and maintainability.

interface TemporaryCalculationResponse {
  getTemporaryCalculations: SocialInsuranceTemporaryCalculation
}

const { data, loading, error } = useQuery<TemporaryCalculationResponse>(

Line range hint 193-228: Extract table rendering logic to helper functions

Consider extracting the filtering and formatting logic to improve readability and maintainability.

const formatAmount = (amount?: number) => 
  amount ? formatCurrency(String(amount)) : '';

const filterNonPaidRows = (rows: Row[]) =>
  rows?.filter(({ name }) => name !== 'Útborgað') ?? [];

// Usage:
{filterNonPaidRows(group?.rows).map((row) => (
  <T.Row key={`row-${row.id}`}>
    <T.Data>{row.name}</T.Data>
    <T.Data align="right">
      {formatAmount(row.months?.[monthIndex]?.amount)}
    </T.Data>
    ...
  </T.Row>
))}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fd128f8 and aecb4c2.

📒 Files selected for processing (1)
  • libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."

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 (1)
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (1)

Line range hint 195-230: Optimize table rendering performance

The table rendering could be optimized to prevent unnecessary re-renders and improve performance.

Consider these improvements:

  1. Memoize the filtered rows:
const filteredRows = useMemo(
  () => group?.rows?.filter(({ name }) => name !== 'Útborgað'),
  [group?.rows]
);
  1. Extract the row rendering into a separate memoized component:
const TableRow = memo(({ row, monthIndex }: { row: Row; monthIndex: number }) => (
  <T.Row>
    <T.Data>{row.name}</T.Data>
    <T.Data align="right" box={{ paddingRight: 0 }}>
      {formatCurrency(String(row.months?.[monthIndex]?.amount))}
    </T.Data>
    <T.Data align="right">
      {row.total && formatCurrency(row.total.toString())}
    </T.Data>
  </T.Row>
));
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between aecb4c2 and d7bde61.

📒 Files selected for processing (1)
  • libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (1)

Pattern libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (2)
libs/application/templates/social-insurance-administration/income-plan/src/fields/TemporaryCalculationTable/index.tsx (2)

94-96: LGTM! Type safety improvement

The addition of type parameters to useQuery enhances type safety and follows the TypeScript guidelines for library code.


33-35: ⚠️ Potential issue

Add missing dependencies to useEffect

The useEffect hook is missing dependencies that could lead to stale closures.

  useEffect(() => {
    setValue('temporaryCalculation.show', false)
-  }, [setValue])
+  }, [setValue, 'temporaryCalculation.show'])

Likely invalid or redundant comment.

@kodiakhq kodiakhq bot merged commit ac1a80f into main Nov 25, 2024
40 checks passed
@kodiakhq kodiakhq bot deleted the feat/use-new-temporary-income-plan-calculation-data branch November 25, 2024 15:13
jonnigs pushed a commit that referenced this pull request Nov 26, 2024
…6933)

* feat(income-plan): Use new temporary income plan calculation data

* defaultValue to current month

* set conditional for month selector

* Add paidOut month

* fallback for month index

* Prevent unnecessary re-render

---------

Co-authored-by: hfhelgason <hfhelgason@deloitte.is>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants