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

fix(web-grants): Various fixes #16985

Merged
merged 10 commits into from
Nov 22, 2024
Merged

fix(web-grants): Various fixes #16985

merged 10 commits into from
Nov 22, 2024

Conversation

thorkellmani
Copy link
Member

@thorkellmani thorkellmani commented Nov 21, 2024

What

  • Change url for the search results from leit -> styrkir
  • Add more crumbs to breadcrumb trail
  • Modified contentful models
  • Dynamic filters
  • Change status logic
  • Add parent org and status to ES model
  • more stuf

Why

  • fixes required

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced breadcrumb navigation in grant details, providing direct links to search results.
    • Added dynamic filtering options for grant statuses in search results.
  • Improvements

    • Updated error handling for grant retrieval to provide clearer user feedback.
    • Improved localization handling in grant components.
    • Streamlined status tag generation for grants, enhancing display clarity.
    • Updated application deadline displays to reflect new status terminology.
  • Bug Fixes

    • Resolved issues with application deadline displays and status handling.
  • Documentation

    • Updated message definitions for improved clarity in the user interface.

@thorkellmani thorkellmani requested review from a team as code owners November 21, 2024 13:47
Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes in this pull request involve modifications across multiple files primarily related to the handling of grants within the application. Key updates include adjustments to routing paths, enhancements to breadcrumb navigation and error handling, localization improvements, and restructuring of GraphQL queries. Additionally, utility functions for generating status tags have been introduced, and the grant model has been streamlined to simplify status handling. Overall, these changes aim to improve the organization and clarity of the code while maintaining existing functionalities.

Changes

File Path Change Summary
apps/web/hooks/useLinkResolver/useLinkResolver.ts Updated routesTemplate for styrkjatorgsearch path from /styrkjatorg/leit to /styrkjatorg/styrkir.
apps/web/screens/Grants/Grant/Grant.tsx Added CustomNextError for 404 handling, updated breadcrumbs to include search results, and introduced searchUrl.
apps/web/screens/Grants/Grant/GrantSidebar.tsx Replaced useIntl with useLocale, updated applicationDeadlineText to applicationDeadlineStatus, and added generateStatusTag utility.
apps/web/screens/Grants/Home/GrantsHome.tsx Added isTag: true to the breadcrumb item for the home page.
apps/web/screens/Grants/SearchResults/SearchResultsContent.tsx Removed TagVariant import, replaced inline status tag logic with generateStatusTag, and updated application deadline display.
apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx Introduced dynamic filters for application statuses, updating filter logic accordingly.
apps/web/screens/Grants/messages.ts Updated results message from "Leitarniðurstöður" to "Styrkir" and added applicationSeeDescription message.
apps/web/screens/Grants/utils.ts Added generateStatusTag function to encapsulate status tag generation logic.
apps/web/screens/queries/Grants.ts Modified GraphQL queries to replace applicationDeadlineText with applicationDeadlineStatus and removed statusText.
libs/cms/src/lib/cms.elasticsearch.service.ts Updated getGrants method to process statuses and organizations parameters individually in query construction.
libs/cms/src/lib/models/grant.model.ts Updated GrantStatus enum, removed applicationDeadlineText, and adjusted mapping logic in mapGrant function.
libs/cms/src/lib/search/importers/grants.service.ts Enhanced doMapping method to include tagging grants with parent organization if applicable.
libs/cms/src/lib/dto/getGrants.input.ts Added import for GrantStatus to expand module dependencies without altering existing functionality.
apps/web/screens/Grants/SearchResults/SearchResults.tsx Replaced parseArray with filterArray for improved query parameter handling and added error handling in fetchGrants.

Suggested labels

deploy-feature

Suggested reviewers

  • thordurhhh
  • Valur

Possibly related PRs


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

🧹 Outside diff range and nitpick comments (13)
apps/web/screens/Grants/utils.ts (2)

6-9: Consider using a discriminated union type for better type safety.

While the current type safety is good, we can make it even better by using a discriminated union type for the return value.

Consider this type improvement:

+type StatusTag = {
+  label: string;
+  variant: TagVariant;
+}

 export const generateStatusTag = (
   status: GrantStatus,
   formatMessage: FormatMessage,
-): { label: string; variant: TagVariant } | undefined => {
+): StatusTag | undefined => {

13-25: Document the semantic meaning of tag variants.

The color variants ('mint', 'rose', 'purple') seem to have specific semantic meanings for different statuses. Consider adding a comment explaining the color coding convention.

Add a comment like this at the top of the function:

/**
 * Generates a status tag with appropriate styling based on grant status:
 * - mint: Open for applications
 * - rose: Closed for applications
 * - purple: Special case, see description
 */
libs/cms/src/lib/models/grant.model.ts (1)

33-34: Consider using an enum for applicationDeadlineStatus

The field follows TypeScript and GraphQL best practices. However, since this represents a status, consider using an enum to restrict possible values and improve type safety.

enum ApplicationDeadlineStatus {
  OPEN = 'OPEN',
  CLOSED = 'CLOSED',
  UPCOMING = 'UPCOMING'
}

@Field(() => ApplicationDeadlineStatus, { nullable: true })
applicationDeadlineStatus?: ApplicationDeadlineStatus
apps/web/screens/Grants/Grant/GrantSidebar.tsx (2)

Line range hint 48-54: Consider adding accessibility attributes for new tab behavior

While opening links in new tabs can be useful, ensure proper accessibility by adding appropriate ARIA attributes and visual indicators.

Consider adding these accessibility enhancements:

 <LinkV2
   {...linkResolver(grant.fund.link.type as LinkType, [
     grant.fund.link.slug,
   ])}
   newTab
   color="blue400"
   underline="normal"
   underlineVisibility="hover"
+  aria-label={`${grant.fund.title} (opens in new tab)`}
 >
   {grant.fund.title}
+  <span className="visually-hidden">(opens in new tab)</span>
 </LinkV2>

Line range hint 1-134: Well-structured component with clean separation of concerns

The component follows React/NextJS best practices with:

  • Proper use of hooks (useMemo for derived data)
  • Clear separation of UI elements and data transformation
  • Type-safe props and GraphQL integration

Consider extracting the panel generation logic into separate components if this pattern is reused across other sidebars in the application.

apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx (1)

Line range hint 23-40: Consider performance optimizations

The component could benefit from memoization and custom hooks to optimize performance and improve code organization.

Consider these improvements:

  1. Memoize filter transformations:
const categoryFilters = useMemo(() => 
  tags?.filter((t) => t.genericTagGroup?.slug === 'grant-category'),
  [tags]
);

const typeFilters = useMemo(() => 
  tags?.filter((t) => t.genericTagGroup?.slug === 'grant-type'),
  [tags]
);
  1. Extract filter logic to a custom hook:
const useGrantFilters = (tags: Array<GenericTag>) => {
  const categoryFilters = useMemo(() => 
    tags?.filter((t) => t.genericTagGroup?.slug === 'grant-category'),
    [tags]
  );

  const typeFilters = useMemo(() => 
    tags?.filter((t) => t.genericTagGroup?.slug === 'grant-type'),
    [tags]
  );

  return { categoryFilters, typeFilters };
};
apps/web/screens/Grants/SearchResults/SearchResultsContent.tsx (2)

57-61: Consider adding type safety to tag generation

The status tag implementation is clean and well-organized. Consider adding type assertion to ensure grant.status is of type GrantStatus.

-                    tag={
-                      grant.status
-                        ? generateStatusTag(grant.status, formatMessage)
-                        : undefined
-                    }
+                    tag={
+                      grant.status
+                        ? generateStatusTag(grant.status as GrantStatus, formatMessage)
+                        : undefined
+                    }

86-92: Address the TODO comment regarding deadline text

The comment indicates that the deadline text implementation is incomplete. This should be addressed before merging.

Would you like me to help implement the deadline text formatting or create an issue to track this task?

apps/web/screens/Grants/Home/GrantsHome.tsx (3)

Line range hint 77-77: Address TODO comment for categories

The TODO comment indicates pending work for category implementation. Since the categories are being mapped and rendered, this comment might be outdated.

Consider either implementing the pending work or removing the comment if it's no longer relevant.


Line range hint 183-184: Address TODO comment for organizations

The comment suggests that more organizations need to be added. This should be tracked and implemented if still relevant.

Would you like me to help create a GitHub issue to track this enhancement?


Line range hint 206-208: Consider NextJS optimization opportunities

While the implementation follows NextJS best practices, consider these optimizations:

  • Add getStaticProps instead of dynamic data fetching if the grant categories don't change frequently
  • Implement proper error boundaries for GraphQL query failures
  • Consider adding loading states for better UX
apps/web/screens/Grants/Grant/Grant.tsx (2)

43-43: Consider memoizing the breadcrumb items array

The breadcrumb items array is recreated on every render. Consider using useMemo to optimize performance:

- const breadcrumbItems = [
+ const breadcrumbItems = useMemo(() => [
    {
      title: 'Ísland.is',
      href: linkResolver('homepage', [], locale).href,
    },
    {
      title: formatMessage(m.home.title),
      href: baseUrl,
    },
    {
      title: formatMessage(m.search.results),
      href: searchUrl,
    },
    {
      title: grant?.name ?? formatMessage(m.home.grant),
      href: currentUrl,
      isTag: true,
    },
-  ]
+  ], [baseUrl, searchUrl, currentUrl, locale, grant?.name, formatMessage])

Also applies to: 59-62


Line range hint 76-162: Consider component decomposition for better maintainability

The grant details section (description, who can apply, how to apply, etc.) contains multiple similar blocks. Consider extracting these into a reusable component to improve maintainability and reduce code duplication.

Example structure:

interface GrantSectionProps {
  title?: string;
  content: SliceType[];
  locale: Locale;
  showDivider?: boolean;
}

const GrantSection: React.FC<GrantSectionProps> = ({
  title,
  content,
  locale,
  showDivider
}) => {
  if (!content?.length) return null;
  
  return (
    <>
      <Box>
        {title && <Text variant="h3">{title}</Text>}
        <Box className="rs_read">
          {webRichText(content, undefined, locale)}
        </Box>
      </Box>
      {showDivider && <Divider />}
    </>
  );
};
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a9f7f91 and b816f95.

⛔ Files ignored due to path filters (1)
  • libs/cms/src/lib/generated/contentfulTypes.d.ts is excluded by !**/generated/**
📒 Files selected for processing (12)
  • apps/web/hooks/useLinkResolver/useLinkResolver.ts (1 hunks)
  • apps/web/screens/Grants/Grant/Grant.tsx (3 hunks)
  • apps/web/screens/Grants/Grant/GrantSidebar.tsx (4 hunks)
  • apps/web/screens/Grants/Home/GrantsHome.tsx (1 hunks)
  • apps/web/screens/Grants/SearchResults/SearchResultsContent.tsx (5 hunks)
  • apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx (2 hunks)
  • apps/web/screens/Grants/messages.ts (2 hunks)
  • apps/web/screens/Grants/utils.ts (1 hunks)
  • apps/web/screens/queries/Grants.ts (2 hunks)
  • libs/cms/src/lib/cms.elasticsearch.service.ts (0 hunks)
  • libs/cms/src/lib/models/grant.model.ts (4 hunks)
  • libs/cms/src/lib/search/importers/grants.service.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • libs/cms/src/lib/cms.elasticsearch.service.ts
🧰 Additional context used
📓 Path-based instructions (11)
apps/web/hooks/useLinkResolver/useLinkResolver.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/Grants/Grant/Grant.tsx (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/Grants/Grant/GrantSidebar.tsx (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/Grants/Home/GrantsHome.tsx (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/Grants/SearchResults/SearchResultsContent.tsx (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/Grants/messages.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/Grants/utils.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/queries/Grants.ts (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
libs/cms/src/lib/models/grant.model.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/cms/src/lib/search/importers/grants.service.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)
apps/web/screens/Grants/utils.ts (1)

1-4: LGTM! Well-organized imports with proper type safety.

The imports are properly typed and follow TypeScript best practices.

apps/web/screens/queries/Grants.ts (2)

12-12: LGTM! Verify components using this query

The field rename from applicationDeadlineText to applicationDeadlineStatus improves semantics and aligns with the model changes.

Let's verify all components using this query have been updated:

✅ Verification successful

Field rename successfully implemented across the codebase

The verification confirms that:

  • No instances of the old applicationDeadlineText field remain in the codebase
  • The new applicationDeadlineStatus field is properly used in all relevant components:
    • GrantSidebar.tsx
    • SearchResultsContent.tsx
    • Grants.ts (queries)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components using GET_GRANTS_QUERY and check for old field usage
rg -l "GET_GRANTS_QUERY" apps/web/screens/ | xargs rg "applicationDeadlineText"

Length of output: 77


Script:

#!/bin/bash
# First, let's find files that use GET_GRANTS_QUERY
rg -l "GET_GRANTS_QUERY" apps/web/

# Then, let's check for any remaining usage of applicationDeadlineText
rg "applicationDeadlineText" apps/web/

# Finally, let's see the actual usage of applicationDeadlineStatus
rg "applicationDeadlineStatus" apps/web/

Length of output: 805


70-71: LGTM! Verify type definitions

The field changes align with the model updates and maintain consistency with GET_GRANTS_QUERY.

Let's verify the GraphQL types are properly defined:

libs/cms/src/lib/models/grant.model.ts (2)

Line range hint 1-124: Well-structured model with proper TypeScript integration

The code follows best practices for a shared library:

  • Strong TypeScript typing with proper decorators
  • Clean exports for tree-shaking
  • Reusable model structure suitable for cross-app usage

14-14: Verify the removal of OPENS_SOON and INACTIVE statuses

The consolidation of statuses could impact existing code. Let's verify all usages of the removed statuses.

✅ Verification successful

Let me try a different search strategy to verify the impact of these status changes.


Status consolidation change is properly implemented

The codebase search shows that:

  • The old statuses (OPENS_SOON and INACTIVE) are not referenced anywhere in the codebase
  • The new SEE_DESCRIPTION status is properly integrated in:
    • The status mapping logic in libs/cms/src/lib/models/grant.model.ts
    • The status handling in apps/web/screens/Grants/utils.ts with appropriate label and styling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of the old status values
echo "Searching for OPENS_SOON usage..."
rg -l "OPENS_SOON" --type ts

echo "Searching for INACTIVE usage..."
rg -l "INACTIVE" --type ts

# Search for components using GrantStatus enum
echo "Searching for components using GrantStatus..."
ast-grep --pattern 'import { $$$, GrantStatus, $$$ } from $path'

Length of output: 373


Script:

#!/bin/bash
# Search for any usage of GrantStatus enum with context
echo "Searching for GrantStatus usage with context..."
rg "GrantStatus\." -A 3 --type ts

# Search for any switch/case statements handling grant statuses
echo "Searching for switch statements with grant status..."
ast-grep --pattern 'switch ($expr) {
  case GrantStatus.$_:
    $$$
}'

# Search for conditional statements checking grant statuses
echo "Searching for conditional checks on grant status..."
rg "(OPENS_SOON|INACTIVE)" --type ts -A 2

Length of output: 1931

apps/web/screens/Grants/Grant/GrantSidebar.tsx (2)

11-12: LGTM: Clean localization refactor

The switch from useIntl to useLocale and the addition of the status tag utility improve code organization and maintainability.

Also applies to: 35-35


75-84: Verify status tag implementation consistency

The status display has been updated to use the new generateStatusTag utility. Let's verify its implementation across the codebase.

✅ Verification successful

Let me gather more information about the status tag generation implementation.


Let me search specifically for the implementation of generateStatusTag utility.


Status tag implementation is consistent with the model

The generateStatusTag utility in apps/web/screens/Grants/utils.ts correctly handles the GrantStatus enum defined in libs/cms/src/lib/models/grant.model.ts. The implementation properly maps grant statuses to appropriate display tags with consistent formatting.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of generateStatusTag and applicationDeadlineStatus

# Check for generateStatusTag usage
echo "Checking generateStatusTag usage patterns:"
ast-grep --pattern 'generateStatusTag($status, $formatMessage)'

# Check for applicationDeadlineStatus references
echo "Checking applicationDeadlineStatus in GraphQL queries:"
rg -A 2 'applicationDeadlineStatus'

Length of output: 2170


Script:

#!/bin/bash
# Search for generateStatusTag implementation and related utilities
echo "Searching for generateStatusTag implementation:"
rg -A 5 "export.*generateStatusTag"

echo "Searching for status tag related types and enums:"
rg -A 5 "enum.*Status|type.*Status"

echo "Searching for other status tag usages in components:"
rg -A 2 "generateStatusTag|StatusTag"

Length of output: 106027


Script:

#!/bin/bash
# Search for generateStatusTag implementation
echo "Searching for generateStatusTag implementation:"
rg -A 10 "export.*generateStatusTag"

# Search for GrantStatus enum
echo "Searching for GrantStatus enum definition:"
rg -A 5 "enum GrantStatus"

Length of output: 1252

apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx (1)

10-10: LGTM: Import statement follows best practices

The addition of GrantStatus import is well-organized alongside related GraphQL schema imports.

apps/web/screens/Grants/messages.ts (2)

51-54: LGTM: New message follows established patterns.

The new 'applicationSeeDescription' message follows the established message definition pattern and is appropriately placed in the search section.


21-21: Verify the impact of terminology change.

The message change from 'Leitarniðurstöður' (Search results) to 'Styrkir' (Grants) makes the UI more specific to grants. This aligns with the routing path changes mentioned in the summary.

Let's verify the usage of this message key to ensure consistent terminology:

✅ Verification successful

Terminology change is consistent and well-placed

The message change from 'Leitarniðurstöður' to 'Styrkir' is used in breadcrumb navigation in both the SearchResults and Grant components, making it a logical change that provides better context. The term appears in expected locations and maintains consistency across the grants section of the application.

  • Used in SearchResults/SearchResults.tsx for the search results page breadcrumb
  • Used in Grant/Grant.tsx for the individual grant view breadcrumb
  • No conflicting or inconsistent usage found elsewhere in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for components using this message key
rg -t tsx -t ts "search\.results" apps/web/screens/Grants

Length of output: 87


Script:

#!/bin/bash
# Search for components using this message key, without file type restrictions
rg "search\.results" apps/web/screens/Grants

Length of output: 495


Script:

#!/bin/bash
# Search for the message ID in the entire codebase
rg "web\.grants\.search\.results" 

Length of output: 35


Script:

#!/bin/bash
# List all files in the Grants directory to understand the structure
fd . apps/web/screens/Grants

Length of output: 511


Script:

#!/bin/bash
# Check the content of the components using this message to understand the context
rg -A 5 "formatMessage\(m\.search\.results\)" apps/web/screens/Grants

Length of output: 914


Script:

#!/bin/bash
# Look for any other similar terminology changes in the codebase
rg "Styrkir" apps/web/screens/Grants

Length of output: 105

libs/cms/src/lib/search/importers/grants.service.ts (1)

Line range hint 1-24: LGTM! Code follows library guidelines.

The implementation adheres to the library coding guidelines with proper TypeScript usage, clear interface implementation, and maintainable dependency injection patterns.

apps/web/screens/Grants/SearchResults/SearchResultsContent.tsx (1)

6-6: LGTM: Import changes are well-organized

The import changes align well with the refactoring to use the new generateStatusTag utility and localization hook.

Also applies to: 15-16

apps/web/screens/Grants/Home/GrantsHome.tsx (3)

Line range hint 31-56: Well-structured component with proper TypeScript usage

The component follows NextJS best practices with:

  • Proper type safety using TypeScript
  • Clean separation of concerns between presentation and container components
  • Effective use of custom hooks for internationalization and routing

Line range hint 182-204: Well-implemented server-side data fetching

The GraphQL integration follows best practices:

  • Proper typing with QueryGetGenericTagsInTagGroupsArgs
  • Handles locale correctly
  • Uses server-side data fetching appropriately

54-54: Verify the isTag prop handling in Breadcrumbs component

The addition of isTag: true suggests a visual or behavioral change in the breadcrumb rendering. Please ensure that the Breadcrumbs component from @island.is/island-ui/core properly handles this prop.

✅ Verification successful

Let me gather more information about the Breadcrumbs component implementation to verify the isTag prop handling.


The isTag prop is properly handled by the Breadcrumbs component

The Breadcrumbs component from @island.is/island-ui/core correctly implements and handles the isTag prop:

  • It's properly typed in the BreadCrumbItem interface
  • When isTag is true, it renders the breadcrumb item using the Tag component instead of plain text
  • The implementation includes proper styling and accessibility considerations
  • The usage pattern is consistent across multiple files in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Breadcrumbs component implementation to verify isTag prop handling
ast-grep --pattern 'interface $_ {
  $$$
  isTag$_
  $$$
}'

# Search for Breadcrumbs usage with isTag prop
rg -A 2 'isTag.*true' 

Length of output: 4200


Script:

#!/bin/bash
# Search for Breadcrumbs component implementation and interface
ast-grep --pattern 'interface BreadcrumbItem {
  $$$
}'

# Look for the actual implementation of how isTag is used
rg -A 5 'const Breadcrumbs' libs/island-ui/core/src/lib/Breadcrumbs/

Length of output: 649


Script:

#!/bin/bash
# Search for the full Breadcrumbs component implementation
cat libs/island-ui/core/src/lib/Breadcrumbs/Breadcrumbs.tsx

# Check if there are any type definitions for BreadcrumbItem
rg -A 5 'interface BreadcrumbItem' libs/island-ui/core/src/lib/Breadcrumbs/

Length of output: 2815

apps/web/screens/Grants/Grant/Grant.tsx (2)

25-25: LGTM: Clean import addition

The CustomNextError import is well-placed and follows the project's import organization pattern.


Line range hint 183-186: LGTM: Proper error handling implementation

The error handling follows NextJS best practices by:

  • Using appropriate 404 status code for missing resources
  • Throwing the error before props are returned
  • Providing a clear error message
apps/web/hooks/useLinkResolver/useLinkResolver.ts (1)

315-315: Verify route change impact and update documentation

The semantic improvement from /leit to /styrkir better reflects the content. However, this change requires verification:

  1. Ensure all components and links using this route are updated
  2. Update any relevant documentation referencing this route
  3. Consider adding a redirect for existing bookmarks

Let's verify the route usage across the codebase:

✅ Verification successful

Let me gather more information about the route usage and potential impacts.


Let me try one final verification with modified commands:


Based on the verification results, I can now provide a final response:

Route change is safe and properly contained

The route change from /styrkjatorg/leit to /styrkjatorg/styrkir is safe as:

  • No references to the old route /styrkjatorg/leit exist in the codebase
  • The new route /styrkjatorg/styrkir is only defined in useLinkResolver.ts
  • All route usages in the Grants feature components (GrantsHome.tsx, SearchResults.tsx, Grant.tsx) use the linkResolver to generate URLs dynamically

The change is properly encapsulated within the link resolver system, and there are no hardcoded references to either the old or new route that would need updating.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential references to the old route and verify new route usage

# Check for old route references
echo "Checking for old route references..."
rg -l "styrkjatorg/leit"

# Check new route usage
echo "Checking new route usage..."
rg -l "styrkjatorg/styrkir"

# Check for potential hardcoded routes in components
echo "Checking for route usage in components..."
ast-grep --pattern 'href="*/styrkjatorg/leit"'

Length of output: 392


Script:

#!/bin/bash
# Check for any dynamic route construction or references
echo "Checking for dynamic route construction..."
rg -A 2 "styrkjatorg" --type ts --type tsx

# Check for potential test files that might need updates
echo "Checking test files..."
fd -e test.ts -e test.tsx -e spec.ts -e spec.tsx -x rg -l "styrkjatorg"

# Check for potential configuration files
echo "Checking configuration files..."
fd -e config.ts -e config.js -x rg -l "styrkjatorg"

# Check for any router.push or similar navigation calls
echo "Checking navigation calls..."
ast-grep --pattern 'router.push($$$"/styrkjatorg/$$$")'

Length of output: 542


Script:

#!/bin/bash
# Check for any route references with proper file type
echo "Checking route references..."
rg -A 2 "styrkjatorg" .

# Check for any Link components using this route
echo "Checking Link components..."
ast-grep --pattern 'Link $$$href$$$styrkjatorg$$$'

# Check for any navigation methods
echo "Checking navigation methods..."
rg "router\.(push|replace)" -A 2

Length of output: 80985

apps/web/screens/Grants/utils.ts Show resolved Hide resolved
libs/cms/src/lib/models/grant.model.ts Outdated Show resolved Hide resolved
libs/cms/src/lib/search/importers/grants.service.ts Outdated Show resolved Hide resolved
Copy link

codecov bot commented Nov 21, 2024

Codecov Report

Attention: Patch coverage is 8.51064% with 43 lines in your changes missing coverage. Please review.

Project coverage is 35.61%. Comparing base (6cf5d56) to head (590235b).

Files with missing lines Patch % Lines
...ibs/cms/src/lib/search/importers/grants.service.ts 7.69% 12 Missing ⚠️
apps/web/screens/Grants/utils.ts 0.00% 11 Missing ⚠️
apps/web/screens/Grants/Grant/GrantSidebar.tsx 0.00% 6 Missing ⚠️
...eens/Grants/SearchResults/SearchResultsContent.tsx 0.00% 5 Missing ⚠️
libs/cms/src/lib/cms.elasticsearch.service.ts 0.00% 4 Missing ⚠️
libs/cms/src/lib/models/grant.model.ts 50.00% 3 Missing ⚠️
apps/web/screens/Grants/Grant/Grant.tsx 0.00% 1 Missing ⚠️
...web/screens/Grants/SearchResults/SearchResults.tsx 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16985      +/-   ##
==========================================
- Coverage   35.62%   35.61%   -0.01%     
==========================================
  Files        6914     6915       +1     
  Lines      146001   146011      +10     
  Branches    41451    41456       +5     
==========================================
- Hits        52011    52009       -2     
- Misses      93990    94002      +12     
Flag Coverage Δ
api 3.34% <ø> (ø)
api-domains-auth-admin 48.49% <ø> (ø)
api-domains-communications 39.53% <17.39%> (-0.06%) ⬇️
application-system-api 38.70% <17.39%> (+<0.01%) ⬆️
application-template-api-modules 27.70% <17.39%> (-0.02%) ⬇️
cms 0.41% <0.00%> (-0.01%) ⬇️
cms-translations 38.85% <17.39%> (-0.06%) ⬇️
judicial-system-api 19.86% <ø> (ø)
services-user-notification 46.72% <17.39%> (-0.03%) ⬇️
web 1.75% <0.00%> (-0.01%) ⬇️

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

Files with missing lines Coverage Δ
apps/web/hooks/useLinkResolver/useLinkResolver.ts 72.13% <ø> (ø)
apps/web/pages/styrkjatorg/styrkir/index.ts 0.00% <ø> (ø)
apps/web/screens/Grants/Home/GrantsHome.tsx 0.00% <ø> (ø)
...reens/Grants/SearchResults/SearchResultsFilter.tsx 0.00% <ø> (ø)
apps/web/screens/Grants/messages.ts 0.00% <ø> (ø)
apps/web/screens/queries/Grants.ts 0.00% <ø> (ø)
libs/cms/src/lib/dto/getGrants.input.ts 63.15% <ø> (ø)
apps/web/screens/Grants/Grant/Grant.tsx 0.00% <0.00%> (ø)
...web/screens/Grants/SearchResults/SearchResults.tsx 0.00% <0.00%> (ø)
libs/cms/src/lib/models/grant.model.ts 47.14% <50.00%> (-0.16%) ⬇️
... and 5 more

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 6cf5d56...590235b. Read the comment docs.

---- 🚨 Try these New Features:

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 21, 2024

Datadog Report

All test runs a57203a 🔗

11 Total Test Services: 0 Failed, 10 Passed
🔻 Test Sessions change in coverage: 4 decreased, 25 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 2.67s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 12.34s 1 no change Link
api-domains-communications 0 0 0 5 0 28.73s 1 decreased (-0.07%) Link
api-domains-license-service 0 0 0 0 0 587.7ms 1 no change Link
application-system-api 0 0 0 34 0 2m 16.14s 1 no change Link
application-template-api-modules 0 0 0 116 0 2m 38.88s 1 no change Link
cms-translations 0 0 0 3 0 32.89s 1 decreased (-0.07%) Link
judicial-system-api 0 0 0 59 0 7.45s 1 no change Link
judicial-system-backend 0 0 0 21214 0 16m 55.17s 1 decreased (-0.03%) Link
services-user-notification 0 0 0 51 0 1m 24.51s 1 decreased (-0.03%) Link

🔻 Code Coverage Decreases vs Default Branch (4)

  • api-domains-communications - jest 48.74% (-0.07%) - Details
  • cms-translations - jest 48.39% (-0.07%) - Details
  • judicial-system-backend - jest 59.23% (-0.03%) - Details
  • services-user-notification - jest 69.27% (-0.03%) - Details

@thorkellmani thorkellmani added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 21, 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 (6)
libs/cms/src/lib/models/grant.model.ts (1)

33-34: Add documentation for the new field

Please add JSDoc comments explaining the purpose and possible values of applicationDeadlineStatus.

+/**
+ * Status text describing the application deadline state
+ * @example "Open until March 1st, 2024"
+ */
 @Field({ nullable: true })
 applicationDeadlineStatus?: string
apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx (2)

76-82: Consider making the status filters more maintainable

While using GrantStatus enum values is an improvement, the implementation could be more maintainable.

Consider this more maintainable approach:

-filters: [
-  {
-    value: GrantStatus.Open.toString().toLowerCase(),
-    label: formatMessage(m.search.applicationOpen),
-  },
-  {
-    value: GrantStatus.Closed.toString().toLowerCase(),
-    label: formatMessage(m.search.applicationClosed),
-  },
-],
+filters: Object.values(GrantStatus).map((status) => ({
+  value: status.toString().toLowerCase(),
+  label: formatMessage(m.search[`application${status}`]),
+})),

This approach:

  • Automatically handles new status values
  • Reduces duplicate code
  • Maintains type safety

Line range hint 22-31: Consider using React Query for filter state management

The current implementation manages filter state through props and callbacks. For better scalability and performance, consider using React Query:

  • Enables server-state synchronization
  • Provides automatic background updates
  • Handles caching and loading states

Example implementation:

const { data: filterState, mutate } = useQuery(['filterState'], 
  () => fetchFilterState(), 
  { 
    initialData: searchState 
  }
);

const handleFilterUpdate = async (categoryId: keyof SearchState, value: unknown) => {
  await mutate({ ...filterState, [categoryId]: value });
};

Also applies to: 45-52

apps/web/screens/Grants/SearchResults/SearchResults.tsx (3)

Line range hint 128-150: Enhance error handling for better user experience

While the error handling is functional, consider these improvements for production-grade error management:

  1. Replace console.error with a proper error logging service
  2. Add error state management to display user-friendly error messages
  3. Implement an error boundary to gracefully handle rendering failures
 const [grants, setGrants] = useState<Array<Grant>>(initialGrants ?? [])
+const [error, setError] = useState<Error | null>(null)
+
 const fetchGrants = useCallback(() => {
   if (initialRender) {
     setInitialRender(false)
     return
   }

   getGrants({
     variables: {
       input: {
         // ... existing input
       },
     },
   })
     .then((res) => {
       if (res.data) {
         setGrants(res.data.getGrants.items)
+        setError(null)
       } else if (res.error) {
         setGrants([])
-        console.error('Error fetching grants', res.error)
+        setError(res.error)
+        errorLoggingService.log('Error fetching grants', res.error)
       }
     })
     .catch((err) => {
       setGrants([])
-      console.error('Error fetching grants', err)
+      setError(err)
+      errorLoggingService.log('Error fetching grants', err)
     })
 }

361-368: Consider enhancing the filterArray utility

The generic utility function is well-typed but could be improved:

  1. Move it to a shared utility file for reuse across components
  2. Add input validation for array elements
  3. Consider adding JSDoc documentation

Consider moving this to a shared utility file (utils/array.ts):

/**
 * Filters out empty or null arrays, returning undefined instead
 * @param array The input array to filter
 * @returns The original array if non-empty, undefined otherwise
 */
export const filterArray = <T extends string | number>(
  array: Array<T> | null | undefined,
  validate?: (item: T) => boolean
): Array<T> | undefined => {
  if (!array?.length) {
    return undefined;
  }
  
  if (validate) {
    const filtered = array.filter(validate);
    return filtered.length ? filtered : undefined;
  }
  
  return array;
};

384-393: Optimize query parameter handling

While the implementation is type-safe, consider reducing repetition:

+const parseQueryArray = (param: unknown) => 
+  filterArray<string>(arrayParser.parseServerSide(param))
+
 input: {
   lang: locale as ContentLanguage,
   page: parseAsInteger.withDefault(1).parseServerSide(query?.page),
   search: parseAsString.parseServerSide(query?.query) ?? undefined,
-  categories: filterArray<string>(
-    arrayParser.parseServerSide(query?.category),
-  ),
-  statuses: filterArray<string>(
-    arrayParser.parseServerSide(query?.status),
-  ),
-  types: filterArray<string>(arrayParser.parseServerSide(query?.type)),
-  organizations: filterArray<string>(
-    arrayParser.parseServerSide(query?.organization),
-  ),
+  categories: parseQueryArray(query?.category),
+  statuses: parseQueryArray(query?.status),
+  types: parseQueryArray(query?.type),
+  organizations: parseQueryArray(query?.organization),
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b816f95 and ac7db98.

⛔ Files ignored due to path filters (1)
  • libs/cms/src/lib/generated/contentfulTypes.d.ts is excluded by !**/generated/**
📒 Files selected for processing (10)
  • apps/web/screens/Grants/Grant/GrantSidebar.tsx (4 hunks)
  • apps/web/screens/Grants/Home/GrantsHome.tsx (1 hunks)
  • apps/web/screens/Grants/SearchResults/SearchResults.tsx (3 hunks)
  • apps/web/screens/Grants/SearchResults/SearchResultsContent.tsx (4 hunks)
  • apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx (3 hunks)
  • apps/web/screens/Grants/messages.ts (2 hunks)
  • libs/cms/src/lib/cms.elasticsearch.service.ts (2 hunks)
  • libs/cms/src/lib/dto/getGrants.input.ts (1 hunks)
  • libs/cms/src/lib/models/grant.model.ts (4 hunks)
  • libs/cms/src/lib/search/importers/grants.service.ts (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • libs/cms/src/lib/dto/getGrants.input.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • apps/web/screens/Grants/Grant/GrantSidebar.tsx
  • apps/web/screens/Grants/Home/GrantsHome.tsx
  • apps/web/screens/Grants/SearchResults/SearchResultsContent.tsx
  • apps/web/screens/Grants/messages.ts
  • libs/cms/src/lib/cms.elasticsearch.service.ts
  • libs/cms/src/lib/search/importers/grants.service.ts
🧰 Additional context used
📓 Path-based instructions (3)
apps/web/screens/Grants/SearchResults/SearchResults.tsx (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx (1)

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

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
libs/cms/src/lib/models/grant.model.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 (3)
libs/cms/src/lib/models/grant.model.ts (1)

Line range hint 1-124: Code follows library guidelines

The implementation properly follows the library coding guidelines:

  • ✓ Exports reusable models and types
  • ✓ Uses TypeScript with proper type definitions
  • ✓ Follows proper tree-shaking practices with named exports
apps/web/screens/Grants/SearchResults/SearchResultsFilter.tsx (2)

10-10: LGTM! Good use of GraphQL schema types

The addition of GrantStatus import from the GraphQL schema improves type safety and maintainability by using centralized enum values instead of hardcoded strings.


114-116: Verify the impact of organization filter changes

The organization value has been changed and some organizations have been removed from the filters.

Let's verify the impact of these changes:

✅ Verification successful

Let me gather more information to verify the impact comprehensively.


Based on the gathered information, I can now provide the final response:

Organization filter changes appear safe to proceed

The changes to organization filters are localized to the search results component and properly reflected in the organization cache. The codebase shows that:

  • Organization filtering is handled generically through filter arrays and query parameters
  • The new organization value 'rannsoknamidstoed-islands-rannis' is properly defined in the cache
  • No hard-coded references to the removed organizations were found in the TypeScript files
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for references to old organization values
rg -l "tonlistarmidstod|kvikmyndastod" --type ts --type tsx

# Check for references to the new organization value
rg "rannsoknamidstoed-islands-rannis" -A 2 -B 2

Length of output: 1011


Script:

#!/bin/bash
# Search for any references to organizations in TypeScript files
rg -t ts "organization.*filter" -A 2 -B 2

# Check for any GraphQL queries or types related to organizations
rg -t graphql -t ts "organization.*type|organization.*query" -A 2 -B 2

# Look for organization-related test files
fd "organization|grant" --type f --extension test.ts --extension test.tsx --extension spec.ts --extension spec.tsx

Length of output: 2869

libs/cms/src/lib/models/grant.model.ts Show resolved Hide resolved
libs/cms/src/lib/models/grant.model.ts Show resolved Hide resolved
@kodiakhq kodiakhq bot merged commit e8c4c81 into main Nov 22, 2024
61 checks passed
@kodiakhq kodiakhq bot deleted the fix/grant-fixes branch November 22, 2024 10:43
jonnigs pushed a commit that referenced this pull request Nov 26, 2024
* fix: ini

* fix: change application deadlineg

* feat: change routing

* fix: missing crumb

* fix: status dynamic message

* fix: multiple stuff

* fix: null check

---------

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.

3 participants