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

chore(inao-cem): Refactor custom components and fetch tax data #17195

Merged
merged 16 commits into from
Dec 12, 2024

Conversation

jonnigs
Copy link
Member

@jonnigs jonnigs commented Dec 10, 2024

What

Remove custom components that are no longer needed
Make logic to fetch tax data better

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

  • New Features

    • Introduced a new component for fetching data based on the selected year.
    • Added new utility functions for extracting and formatting financial data.
    • Expanded type definitions for caretakers and tax information.
    • Added a new constant for donations to the cemetery fund.
  • Bug Fixes

    • Updated conditions for displaying fields based on cemetery financial limits.
  • Refactor

    • Streamlined data handling and component logic in several sections.
    • Reorganized utility functions for better modularity.
  • Removals

    • Removed several outdated components and functions related to financial calculations.

Copy link
Contributor

coderabbitai bot commented Dec 10, 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.

warning [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning eslint > @humanwhocodes/[email protected]: Use @eslint/config-array instead
warning eslint > @humanwhocodes/config-array > @humanwhocodes/[email protected]: Use @eslint/object-schema instead
warning eslint > file-entry-cache > flat-cache > [email protected]: Rimraf versions prior to v4 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob > [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning jest > @jest/core > jest-config > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > jest-runtime > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > @jest/reporters > [email protected]: Glob versions prior to v9 are no longer supported
warning jest > @jest/core > @jest/transform > babel-plugin-istanbul > test-exclude > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > puppeteer-core > [email protected]: Rimraf versions prior to v4 are no longer supported
warning storybook > @storybook/cli > puppeteer-core > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > tempy > del > [email protected]: Rimraf versions prior to v4 are no longer supported
warning storybook > @storybook/cli > jscodeshift > temp > [email protected]: Rimraf versions prior to v4 are no longer supported
warning storybook > @storybook/cli > jscodeshift > temp > rimraf > [email protected]: Glob versions prior to v9 are no longer supported
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead.
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead.
warning storybook > @storybook/cli > jscodeshift > @babel/[email protected]: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead.
warning next-auth > [email protected]: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
warning next-auth > [email protected]: this version is no longer supported
warning next-auth > @next-auth/typeorm-legacy-adapter > typeorm > [email protected]: Glob versions prior to v9 are no longer supported
warning @nx/next > @nx/webpack > stylus > [email protected]: Glob versions prior to v9 are no longer supported
warning @nx/next > @nx/webpack > webpack-dev-server > [email protected]: Rimraf versions prior to v4 are no longer supported
warning @nx/next > @nx/webpack > fork-ts-checker-webpack-plugin > [email protected]: this will be v4
warning @nx/next > @nx/webpack > webpack-dev-server > webpack-dev-middleware > [email protected]: this will be v4
warning workspace-aggregator-8782462b-9e62-4ac2-b844-a44f38fb520d > [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning "@nx/eslint > @nx/js > [email protected]" has unmet peer dependency "@types/node@".
warning "@nx/next > @babel/[email protected]" has unmet peer dependency "@babel/core@^7.0.0-0".
warning "styled-components > babel-plugin-styled-components > @babel/[email protected]" has unmet peer dependency "@babel/core@^7.0.0-0".
warning " > [email protected]" has unmet peer dependency "react-is@>= 16.8.0".
warning "@nx/react > [email protected]" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0".
warning " > [email protected]" has unmet peer dependency "@types/node@
".
warning "@vanilla-extract/next-plugin > @vanilla-extract/[email protected]" has unmet peer dependency "webpack@^4.30.0 || ^5.20.2".
warning " > [email protected]" has incorrect peer dependency "react@^16.13.1 || ^17".
warning " > [email protected]" has incorrect peer dependency "react-dom@^16.13.1 || ^17".
warning "next-auth > @next-auth/[email protected]" has unmet peer dependency "@prisma/client@^2.16.1".
warning " > [email protected]" has incorrect peer dependency "next@^13.4".
warning "@nx/next > [email protected]" has unmet peer dependency "webpack@^5.1.0".

Walkthrough

The changes in this pull request primarily involve modifications to the .github/CODEOWNERS file, where new ownership entries have been added for various project paths related to inao templates and modules, assigning ownership to the @island-is/norda team. Additionally, several files have been altered, including the removal of components, updates to existing components, and the introduction of new utility functions for managing financial data related to cemetery operations.

Changes

File Change Summary
.github/CODEOWNERS Added ownership entries for multiple paths, assigning them to @island-is/norda.
libs/application/templates/inao/financial-statement-cemetery/src/dataProviders/index.ts Modified export for IdentityApi, now exporting IdentityApiProvider with new configuration.
libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryIncomeLimit/index.tsx Removed the CemeteryIncomeLimit component.
libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/AboutOverview.tsx Updated answers prop type and simplified data extraction using a new utility function.
libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/CapitalNumbersOverview.tsx Updated answers prop type and simplified data extraction using a new utility function.
libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/index.tsx Refactored data handling logic, replacing getValueViaPath with getOverviewNumbers.
libs/application/templates/inao/financial-statement-cemetery/src/fields/FetchDataBasedOnSelectedYear/index.tsx Introduced a new component for fetching data based on the selected year.
libs/application/templates/inao/financial-statement-cemetery/src/fields/PowerOfAttorney/index.tsx Removed the PowerOfAttorneyFields component.
libs/application/templates/inao/financial-statement-cemetery/src/fields/index.ts Removed exports for PowerOfAttorneyFields, CemeteryOverview, and CemeteryIncomeLimit; added export for FetchDataBasedOnSelectedYear.
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryCaretakerSection/caretakerMultiField.ts Removed caretakerMultiField definition.
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryCaretakerSection/index.ts Added new multi-field structure for cemetery caretakers, with conditional rendering based on financial limits.
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryFinancialStatementSection/index.ts Updated condition for displaying file upload field based on total income limits.
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/capitalNumberSubSection.ts Updated import statement for sumCapitalNumbers function.
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/equityAndLiabilitySubSection.ts Restructured imports for helper functions.
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/opperatingCostSubSection.ts Updated component references and IDs related to fetching data based on the selected year.
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/clientInfoSection/index.ts Replaced buildCustomField with buildTextField for power of attorney fields and streamlined data retrieval.
libs/application/templates/inao/financial-statement-cemetery/src/hooks/useTotals.ts Removed the useTotals custom hook.
libs/application/templates/inao/financial-statement-cemetery/src/lib/dataSchema.ts Updated import for isPositiveNumberInString and maintained existing Zod schemas.
libs/application/templates/inao/financial-statement-cemetery/src/types/types.ts Added new types: CareTaker, TaxInfoItem, and TaxInfoData.
libs/application/templates/inao/financial-statement-cemetery/src/utils/constants.ts Added DONATIONS_TO_CEMETERYFUND constant to TaxInfoTypes enum.
libs/application/templates/inao/financial-statement-cemetery/src/utils/currency.ts Introduced new utility functions for currency handling: currencyStringToNumber, formatCurrency, and isPositiveNumberInString.
libs/application/templates/inao/financial-statement-cemetery/src/utils/helpers.ts Removed several financial calculation functions and added getCareIncomeAndBurialRevenueAndGrant and getTaxInfoFromAnswers functions.
libs/application/templates/inao/financial-statement-cemetery/src/utils/overviewUtils.ts Introduced utility functions for extracting and formatting financial data: getOverviewNumbers, getAboutOverviewNumbers, and getCapitalNumbersOverviewNumbers.
libs/application/templates/inao/financial-statement-cemetery/src/utils/sums.ts Introduced utility functions for calculating financial metrics related to cemetery operations.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • Toti91
  • robertaandersen

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. (Experiment)
  • @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 Dec 10, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 35.76%. Comparing base (992ef02) to head (3ba2741).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #17195   +/-   ##
=======================================
  Coverage   35.75%   35.76%           
=======================================
  Files        6935     6936    +1     
  Lines      148065   148114   +49     
  Branches    42211    42218    +7     
=======================================
+ Hits        52942    52974   +32     
- Misses      95123    95140   +17     
Flag Coverage Δ
api 3.33% <ø> (ø)
api-domains-auth-admin 48.49% <ø> (ø)
api-domains-communications 39.39% <ø> (ø)
application-system-api 38.74% <ø> (+<0.01%) ⬆️
application-template-api-modules 27.82% <ø> (ø)
application-ui-shell 22.47% <ø> (ø)
cms 0.39% <ø> (ø)
cms-translations 38.72% <ø> (ø)
judicial-system-api 20.16% <ø> (ø)
services-user-notification 46.53% <ø> (ø)
web 2.42% <ø> (ø)

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

see 26 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 992ef02...3ba2741. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Dec 10, 2024

Datadog Report

All test runs 2d2f13c 🔗

13 Total Test Services: 0 Failed, 12 Passed
➡️ Test Sessions change in coverage: 34 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 3.05s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 13.45s 1 no change Link
api-domains-communications 0 0 0 5 0 35.6s 1 no change Link
api-domains-license-service 0 0 0 0 0 499.92ms 1 no change Link
application-system-api 0 0 0 46 0 2m 35.13s 1 no change Link
application-template-api-modules 0 0 0 118 0 2m 5.38s 1 no change Link
application-ui-shell 0 0 0 74 0 30.96s 1 no change Link
cms-translations 0 0 0 3 0 34.53s 1 no change Link
judicial-system-api 0 0 0 61 0 6.79s 1 no change Link
judicial-system-backend 0 0 0 21299 0 24m 59.57s 1 no change Link

@jonnigs jonnigs marked this pull request as ready for review December 10, 2024 22:42
@jonnigs jonnigs requested review from a team as code owners December 10, 2024 22:42
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: 7

🧹 Outside diff range and nitpick comments (19)
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/equityAndLiabilitySubSection.ts (3)

18-21: LGTM! Good reorganization of utility functions.

The relocation of financial calculation functions to a dedicated sums module improves code organization and maintainability.

Consider using barrel exports (index.ts) to simplify these deep relative imports:

// libs/application/templates/inao/financial-statement-cemetery/src/utils/index.ts
export * from './sums';

This would allow shorter imports like: import { sumTotalEquity } from '../../../utils'


Line range hint 23-166: Consider enhancing type safety for form values.

The component structure is well-organized and reusable. However, to improve type safety and maintainability:

Consider defining explicit TypeScript interfaces for the form values:

interface EquityAndLiabilityFormData {
  fixedAssetsTotal: number;
  currentAssets: number;
  longTerm: number;
  shortTerm: number;
  equityAtTheBeginningOfTheYear: number;
  revaluationDueToPriceChanges: number;
  reevaluateOther: number;
}

This would provide better type checking and autocompletion when accessing form values in the utility functions.


Line range hint 1-21: Improve import readability while maintaining tree-shaking benefits.

While the current import structure supports effective tree-shaking:

  1. Consider using a more descriptive alias than 'm' for messages:
import { messages } from '../../../lib/messages'
  1. Consider grouping related builder imports:
import {
  // Field builders
  buildTextField,
  buildDisplayField,
  
  // Section builders
  buildSubSection,
  buildMultiField,
  
  // Helper builders
  buildAlertMessageField,
  buildDescriptionField,
} from '@island.is/application/core'
libs/application/templates/inao/financial-statement-cemetery/src/utils/helpers.ts (1)

Line range hint 25-37: Typo in function name: 'isCemetryUnderFinancialLimit' should be 'isCemeteryUnderFinancialLimit'

The function name contains a typo; 'Cemetry' should be corrected to 'Cemetery' to maintain consistency and avoid confusion.

Apply this diff to correct the function name:

-export const isCemetryUnderFinancialLimit = (answers: FormValue) => {
+export const isCemeteryUnderFinancialLimit = (answers: FormValue) => {
libs/application/templates/inao/financial-statement-cemetery/src/utils/currency.ts (3)

1-7: Ensure proper handling of decimal separators in currencyStringToNumber

The current implementation removes commas, periods, and spaces, which might inadvertently strip decimal separators. Consider handling decimal separators explicitly to accurately parse values with decimals.

Suggested change:

-export const currencyStringToNumber = (str: string) => {
-  if (!str) {
-    return str
-  }
-  const cleanString = str.replace(/[,\s]+|[.\s]+/g, '')
-  return parseInt(cleanString, 10)
+export const currencyStringToNumber = (str: string) => {
+  if (!str) {
+    return str
+  }
+  const normalizedStr = str.replace(/\s+/g, '')
+  const cleanString = normalizedStr.replace(',', '.')
+  return parseFloat(cleanString)
}

9-12: Handle decimal values properly in formatCurrency

If answer includes decimal values, the current formatting may not display them correctly. Consider formatting decimal values appropriately to ensure correct display.

Suggested change:

-export const formatCurrency = (answer?: string) => {
-  if (!answer) return '0. kr'
-  return answer.replace(/\B(?=(\d{3})+(?!\d))/g, '.') + ' kr.'
+export const formatCurrency = (answer?: string) => {
+  if (!answer) return '0 kr.'
+  const number = parseFloat(answer)
+  return number.toLocaleString('is-IS', { style: 'currency', currency: 'ISK' })
}

14-16: Improve input validation in isPositiveNumberInString

If input is not a valid number, Number(input) returns NaN, and the function returns false. Consider explicitly checking for NaN to handle invalid inputs appropriately.

Suggested change:

export const isPositiveNumberInString = (input: string) => {
-  return Number(input) >= 0
+  const num = Number(input)
+  return !isNaN(num) && num >= 0
}
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryFinancialStatementSection/index.ts (2)

3-3: Fix typo in imported function name

The helper function name contains a typo: isCemetryUnderFinancialLimit should be isCemeteryUnderFinancialLimit.


7-9: Add type annotation for condition parameter

The answers parameter in the condition function lacks type annotation. Consider adding appropriate type information for better type safety and code maintainability.

-  condition: (answers) => {
+  condition: (answers: FormValue) => {
     return !isCemetryUnderFinancialLimit(answers)
   },
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryCaretakerSection/index.ts (3)

8-8: Fix typo in imported function name

The helper function name contains a typo: isCemetryUnderFinancialLimit should be isCemeteryUnderFinancialLimit.


11-14: Fix typo in section name and add type annotation

The section name contains a typo ("Careteker") and the condition parameter lacks type annotation.

-export const cemeteryCaretekerSection = buildSection({
+export const cemeteryCaretakerSection = buildSection({
-  condition: (answers) => {
+  condition: (answers: FormValue) => {
     return isCemetryUnderFinancialLimit(answers)
   },

23-28: Consider extracting component name to a constant

The component name 'CemeteryCaretaker' is used as a string literal. Consider extracting it to a constant to prevent typos and enable easier refactoring.

+const CEMETERY_CARETAKER_COMPONENT = 'CemeteryCaretaker' as const;

 buildCustomField({
   id: 'cemeteryCaretaker',
   title: m.cemeteryBoardmembers,
-  component: 'CemeteryCaretaker',
+  component: CEMETERY_CARETAKER_COMPONENT,
   childInputIds: Object.values(CEMETERYCARETAKER),
 }),
libs/application/templates/inao/financial-statement-cemetery/src/types/types.ts (2)

50-54: Consider using type composition for similar structures

The CareTaker type has identical structure to BoardMember. Consider using type composition to avoid duplication and maintain consistency.

-export type CareTaker = {
-  nationalId: string
-  name: string
-  role: string
-}
+export type CareTaker = BoardMember

Also, consider renaming to Caretaker to follow consistent naming conventions (camelCase for variables/types).


56-64: Enhance type safety for TaxInfo types

Consider making the types more specific:

  1. Add literal type for __typename
  2. Consider using an enum for key values if they are predefined
+export enum TaxInfoKey {
+  // Add your specific keys here
+  KEY_1 = 1,
+  KEY_2 = 2,
+}

 export type TaxInfoItem = {
-  __typename: string
-  key: number
+  __typename: 'TaxInfoItem'
+  key: TaxInfoKey
   value: string
 }
libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/AboutOverview.tsx (1)

30-32: Consider using formatNationalId consistently

The formatNationalId function is imported but not used for formatting the national ID.

-            value={nationalId ? nationalId : '-'}
+            value={nationalId ? formatNationalId(nationalId) : '-'}
libs/application/templates/inao/financial-statement-cemetery/src/utils/overviewUtils.ts (1)

146-171: Add TypeScript interface for better type safety

The function would benefit from a clearly defined return type interface.

interface AboutOverview {
  fullName: string;
  nationalId: string;
  powerOfAttorneyName?: string;
  powerOfAttorneyNationalId?: string;
  email: string;
  phoneNumber: string;
}

export const getAboutOverviewNumbers = (answers: FormValue): AboutOverview => {
  // existing implementation
}
libs/application/templates/inao/financial-statement-cemetery/src/lib/dataSchema.ts (1)

Line range hint 201-219: Fix incorrect age validation syntax

There's a syntax error in the age validation that will cause it to always return false.

-      .refine((val) => {
-        return (
-          val ? kennitala.info(val).age < 18 : false,
-          {
-            params: m.nationalIdAgeError,
-          }
-        )
-      }),
+      .refine(
+        (val) => val ? kennitala.info(val).age >= 18 : false,
+        {
+          params: m.nationalIdAgeError,
+        }
+      ),
libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/index.tsx (2)

33-63: Consider adding explicit TypeScript types for financial data.

While the refactoring to use getOverviewNumbers improves maintainability, consider adding explicit types for the destructured financial values to enhance type safety and documentation.

Example:

interface FinancialOverviewData {
  careIncome: string;
  burialRevenue: string;
  // ... other financial fields
  cemeteryCaretakers?: Array<{
    name: string;
    nationalId: string;
    role: string;
  }>;
}

const {
  careIncome,
  burialRevenue,
  // ...
}: FinancialOverviewData = getOverviewNumbers(application.answers);

69-69: Consider using React Context for sharing application data.

The current pattern of passing application.answers directly to child components could lead to prop drilling. Consider using React Context to make the application data available to all components that need it.

Example implementation:

// Create a context
const ApplicationContext = React.createContext<Application | undefined>(undefined);

// Wrap the component tree
export const CemeteryOverview = ({ application }: FieldBaseProps) => {
  return (
    <ApplicationContext.Provider value={application}>
      <Box marginBottom={2}>
        <AboutOverview />
        <CapitalNumberOverview />
        {/* ... */}
      </Box>
    </ApplicationContext.Provider>
  );
};

// In child components
const AboutOverview = () => {
  const application = useContext(ApplicationContext);
  // Use application.answers directly
};

Also applies to: 149-149

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1093822 and d4f8889.

📒 Files selected for processing (24)
  • .github/CODEOWNERS (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/dataProviders/index.ts (2 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryIncomeLimit/index.tsx (0 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/AboutOverview.tsx (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/CapitalNumbersOverview.tsx (2 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/index.tsx (4 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/FetchDataBasedOnSelectedYear/index.tsx (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/PowerOfAttorney/index.tsx (0 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/index.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryCaretakerSection/caretakerMultiField.ts (0 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryCaretakerSection/index.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryFinancialStatementSection/index.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/capitalNumberSubSection.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/equityAndLiabilitySubSection.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/opperatingCostSubSection.ts (2 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/clientInfoSection/index.ts (2 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/hooks/useTotals.ts (0 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/lib/dataSchema.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/types/types.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/utils/constants.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/utils/currency.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/utils/helpers.ts (3 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/utils/overviewUtils.ts (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/utils/sums.ts (1 hunks)
💤 Files with no reviewable changes (4)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryIncomeLimit/index.tsx
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryCaretakerSection/caretakerMultiField.ts
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/PowerOfAttorney/index.tsx
  • libs/application/templates/inao/financial-statement-cemetery/src/hooks/useTotals.ts
✅ Files skipped from review due to trivial changes (1)
  • libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/capitalNumberSubSection.ts
🧰 Additional context used
📓 Path-based instructions (18)
libs/application/templates/inao/financial-statement-cemetery/src/utils/constants.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/inao/financial-statement-cemetery/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/inao/financial-statement-cemetery/src/dataProviders/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/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryFinancialStatementSection/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/inao/financial-statement-cemetery/src/lib/dataSchema.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/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/opperatingCostSubSection.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/inao/financial-statement-cemetery/src/types/types.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/inao/financial-statement-cemetery/src/fields/CemeteryOverview/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/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/equityAndLiabilitySubSection.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/inao/financial-statement-cemetery/src/fields/CemeteryOverview/CapitalNumbersOverview.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/inao/financial-statement-cemetery/src/fields/CemeteryOverview/AboutOverview.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/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryCaretakerSection/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/inao/financial-statement-cemetery/src/utils/currency.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/inao/financial-statement-cemetery/src/forms/applicationForm/clientInfoSection/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/inao/financial-statement-cemetery/src/utils/overviewUtils.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/inao/financial-statement-cemetery/src/fields/FetchDataBasedOnSelectedYear/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/inao/financial-statement-cemetery/src/utils/helpers.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/inao/financial-statement-cemetery/src/utils/sums.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 (18)
libs/application/templates/inao/financial-statement-cemetery/src/utils/helpers.ts (2)

76-109: Function getCareIncomeAndBurialRevenueAndGrant implemented correctly

The function properly retrieves and returns the specified tax information.


112-134: Function getTaxInfoFromAnswers implemented correctly

The function correctly extracts tax information from the provided answers.

libs/application/templates/inao/financial-statement-cemetery/src/fields/index.ts (1)

3-3: Exporting FetchDataBasedOnSelectedYear is appropriate

The new component FetchDataBasedOnSelectedYear is correctly exported.

libs/application/templates/inao/financial-statement-cemetery/src/dataProviders/index.ts (1)

16-21: Configuration of IdentityApiProvider is appropriate

The IdentityApi is correctly configured with includeActorInfo: true and exported as IdentityApiProvider.

libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/CapitalNumbersOverview.tsx (2)

5-11: LGTM! Type safety improvements

Good refactoring to use the common FormValue type and extract the prop type definition. This improves type safety and maintainability.


15-16: Verify the utility function implementation

The refactoring to use getCapitalNumbersOverviewNumbers looks good, but let's verify its implementation.

Also applies to: 26-37

✅ Verification successful

Implementation verified successfully

The getCapitalNumbersOverviewNumbers utility function is properly implemented in overviewUtils.ts. It correctly:

  • Takes form answers as input
  • Uses getValueViaPath to safely access nested values from the answers object
  • Uses formatCurrency from UI components to format the currency values
  • Returns an object with properly formatted capitalIncome, capitalCost, and totalCapital values

Both helper functions (getValueViaPath and formatCurrency) are well-established utilities used throughout the codebase, with formatCurrency specifically handling currency formatting by adding thousand separators and the 'kr.' suffix.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the utility function implementation
ast-grep --pattern 'export const getCapitalNumbersOverviewNumbers = ($params) => {
  $$$
}'

Length of output: 93


Script:

#!/bin/bash
# Let's try a broader search pattern to find the function implementation
rg -l "getCapitalNumbersOverviewNumbers"

# Then let's look at the content of files that contain this function
rg "getCapitalNumbersOverviewNumbers" -A 10

Length of output: 4787


Script:

#!/bin/bash
# Let's verify the helper functions used within getCapitalNumbersOverviewNumbers
rg "formatCurrency|getValueViaPath" -A 5

Length of output: 68760

libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/AboutOverview.tsx (1)

9-21: LGTM! Clean data extraction

Good refactoring to use the utility function for data extraction. The destructuring makes the code more readable.

libs/application/templates/inao/financial-statement-cemetery/src/fields/FetchDataBasedOnSelectedYear/index.tsx (1)

37-43: ⚠️ Potential issue

Add missing dependencies to useEffect

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

-  }, [data, setValue])
+  }, [data, setValue, CEMETERYOPERATIONIDS.incomeLimit])

Likely invalid or redundant comment.

libs/application/templates/inao/financial-statement-cemetery/src/utils/constants.ts (1)

29-29: Verify the tax info type code usage

The addition of DONATIONS_TO_CEMETERYFUND = 334 to TaxInfoTypes looks good, but let's ensure consistent usage across the codebase.

✅ Verification successful

Let me analyze the usage of the new tax info type code by searching for references to DONATIONS_TO_CEMETERYFUND in TypeScript files.


Let me check how this enum value is being used in the financial statements client to ensure consistent usage.


Tax info type code 334 is consistently used for cemetery fund donations

The code 334 for DONATIONS_TO_CEMETERYFUND is consistently used across the codebase:

  • Defined as an enum value in constants.ts
  • Used in helpers.ts for tax info type filtering
  • Properly mapped in the financial statements client service
  • Documented in types with the correct Icelandic description "Framlög til kirkjugarðasjóðs"
  • Verified in test specifications
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new tax info type code
# Search for direct usage of the number 334 to ensure it's not hardcoded elsewhere
rg -n "334" --type ts

# Search for references to DONATIONS_TO_CEMETERYFUND
rg "DONATIONS_TO_CEMETERYFUND" --type ts

Length of output: 84435


Script:

#!/bin/bash
# Search for references to DONATIONS_TO_CEMETERYFUND in TypeScript files
rg -A 3 "DONATIONS_TO_CEMETERYFUND" --type ts

Length of output: 871


Script:

#!/bin/bash
# Search for references to the value 334 in financial statements related files
rg -A 3 "334" --type ts libs/clients/financial-statements-inao/

Length of output: 1716

libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/clientInfoSection/index.ts (3)

62-72: LGTM: Improved type-safe data access for power of attorney national ID

The implementation uses getValueViaPath for safer access to nested properties, reducing the risk of runtime errors.


74-83: LGTM: Improved type-safe data access for power of attorney name

The implementation uses getValueViaPath for safer access to nested properties, reducing the risk of runtime errors.


90-104: LGTM: Enhanced contact information field implementations

The changes improve type safety and consistency by:

  • Using getValueViaPath for safer property access
  • Using specialized buildPhoneField for phone number input
libs/application/templates/inao/financial-statement-cemetery/src/forms/applicationForm/cemeteryKeyNumbersSection/opperatingCostSubSection.ts (2)

15-15: LGTM: Improved module organization

Moving sum-related functions to a dedicated utility file improves code organization and maintainability.


27-29: LGTM: Enhanced component naming and purpose

The changes improve clarity by:

  • Using a more descriptive ID 'fetchDataBasedOnYear'
  • Using a component name that better reflects its functionality
✅ Verification successful

Component change introduces expanded functionality

The new FetchDataBasedOnSelectedYear component is a significant enhancement over the old CemeteryIncomeLimit component:

  • It fetches both financial limits and tax information based on the selected year
  • Adds functionality to populate care income, burial revenue, grants, and donations
  • Maintains backward compatibility by including the original income limit functionality
  • Uses updated GraphQL queries and constants

The change is more than just a rename - it's a functional expansion that better serves the form's requirements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new component exists and the old one is removed
# Check if the new component exists
fd "FetchDataBasedOnSelectedYear" --type f --extension tsx --extension ts

# Check if the old component is fully removed
fd "CemeteryIncomeLimit" --type f --extension tsx --extension ts

Length of output: 138


Script:

#!/bin/bash
# Let's try a broader search using ripgrep to find any references to these components
rg "FetchDataBasedOnSelectedYear" -l
rg "CemeteryIncomeLimit" -l

# Also search for any similar component names that might be related
rg "FetchData.*Year" -l

Length of output: 1013


Script:

#!/bin/bash
# Let's check the content of both components to verify the functionality
cat libs/application/templates/inao/financial-statement-cemetery/src/fields/FetchDataBasedOnSelectedYear/index.tsx
cat libs/application/templates/financial-statements-inao/src/fields/CemetryIncomeLimit/index.tsx

Length of output: 4220

libs/application/templates/inao/financial-statement-cemetery/src/utils/overviewUtils.ts (1)

173-189: LGTM! Well-structured and consistent formatting

The function maintains good separation of concerns and ensures consistent currency formatting.

libs/application/templates/inao/financial-statement-cemetery/src/lib/dataSchema.ts (1)

6-8: LGTM! Import reorganization looks good

The movement of isPositiveNumberInString to the currency utils makes logical sense.

.github/CODEOWNERS (1)

241-247: LGTM! Ownership assignments are consistent.

The new entries follow the established pattern and correctly assign ownership of inao-related templates and modules to the @island-is/norda team.

libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/index.tsx (1)

23-25: LGTM! Well-structured utility imports.

The new utility imports improve code modularity and follow good tree-shaking practices by importing specific functions.

Copy link
Member

@svanaeinars svanaeinars left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Member

@HjorturJ HjorturJ left a comment

Choose a reason for hiding this comment

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

LGTM

@jonnigs jonnigs added the automerge Merge this PR as soon as all checks pass label Dec 11, 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: 4

🧹 Outside diff range and nitpick comments (2)
libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/index.tsx (1)

30-63: Consider breaking down the overview numbers into logical groups

While the current implementation successfully consolidates the data extraction logic, the large number of destructured values (30+) could be organized into logical groups for better maintainability.

Consider grouping related values into separate objects:

const {
  income: { careIncome, burialRevenue, /* ... */ },
  expenses: { payroll, funeralCost, /* ... */ },
  assets: { fixedAssetsTotal, currentAssets, /* ... */ },
  liabilities: { longTerm, shortTerm, /* ... */ },
  equity: { equityAtTheBeginningOfTheYear, /* ... */ },
  metadata: { email, fileName, /* ... */ }
} = getOverviewNumbers(application.answers)
libs/application/templates/inao/financial-statement-cemetery/src/utils/sums.ts (1)

11-225: Specify explicit return types for utility functions

To enhance type safety and maintainability, consider specifying explicit return types for all utility functions. This practice improves code readability and helps prevent potential type-related issues.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6bc8d69 and 4c90cf1.

📒 Files selected for processing (3)
  • .github/CODEOWNERS (1 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/index.tsx (4 hunks)
  • libs/application/templates/inao/financial-statement-cemetery/src/utils/sums.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/application/templates/inao/financial-statement-cemetery/src/fields/CemeteryOverview/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/inao/financial-statement-cemetery/src/utils/sums.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/inao/financial-statement-cemetery/src/fields/CemeteryOverview/index.tsx (3)

23-25: LGTM: Well-structured utility imports

The new utility imports follow good modularization practices and maintain proper TypeScript usage, enhancing reusability across the application.


69-69: LGTM: Consistent prop passing pattern

The direct passing of application.answers to child components maintains consistency and eliminates unnecessary intermediate variables.

Also applies to: 149-149


229-231: Simplify the conditional rendering logic

The current condition has redundant checks. The length check is unnecessary when already checking if cemeteryCaretakers exists.

Apply this simplification:

-      {cemeteryUnderFinancialLimit &&
-      cemeteryCaretakers &&
-      cemeteryCaretakers.length > 0 ? (
+      {cemeteryUnderFinancialLimit && cemeteryCaretakers?.length ? (
libs/application/templates/inao/financial-statement-cemetery/src/utils/sums.ts (1)

11-225: Extract a reusable utility function to reduce code duplication

There is duplicated code in summing numerical values from strings across multiple functions. Consider creating a reusable utility function that handles the conversion and summation, which will reduce code duplication and enhance maintainability.

.github/CODEOWNERS (1)

241-248: Ownership assignments look appropriate

The new CODEOWNERS entries for the inao templates correctly assign ownership to @island-is/norda, ensuring proper responsibility for these modules.

@kodiakhq kodiakhq bot merged commit b22fd0a into main Dec 12, 2024
67 checks passed
@kodiakhq kodiakhq bot deleted the chore/inao-cem-income-limit branch December 12, 2024 22:26
jonnigs added a commit that referenced this pull request Dec 16, 2024
* chore: houskeeping, split up files and make code more radable

* chore: refactor out custom components

* fix: remove imports from codeowners

* chore: remove console.log

* chore: add loading state

* chore: simplify logic

* fix: coderabbit comments

* fix: match indentation to lint

* fix: codeowners

* chore: add space to match indentation

* chore: remove the inao folder from codeowners

* chore: .

* fix: typo in path

* fix: indentation

---------

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
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants