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(regulations-admin): Minor fixes for affected #16143

Merged
merged 4 commits into from
Sep 25, 2024

Conversation

thordurhhh
Copy link
Member

@thordurhhh thordurhhh commented Sep 25, 2024

What

Minor fixes for affected

Why

Bugs need fixing

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 several utility functions for improved processing of regulation amendments, including enhanced title extraction and grouping logic.
    • Enhanced formatting options for affected items based on date consistency.
    • Added functionality to check if all additions share the same date.
  • Bug Fixes

    • Improved handling of article titles for better display and formatting.

@thordurhhh thordurhhh added the automerge Merge this PR as soon as all checks pass label Sep 25, 2024
@thordurhhh thordurhhh requested a review from a team as a code owner September 25, 2024 01:26
Copy link
Contributor

coderabbitai bot commented Sep 25, 2024

Walkthrough

The pull request consolidates utility functions for regulation amendment formatting and enhances the logic for displaying affected items. It introduces a new type definition AdditionObject and a utility function allSameDay to check if all instances share the same date. The formatAffectedAndPlaceAffectedAtEnd function is updated to conditionally format affected items based on a hideAffected parameter. Additionally, the handling of article titles is improved, and redundant functions are removed.

Changes

Files Change Summary
libs/portals/admin/regulations-admin/src/utils/formatAmendingRegulation.ts Consolidated utility functions, updated formatAffectedAndPlaceAffectedAtEnd, formatAmendingRegBody, and formatAmendingBodyWithArticlePrefix functions to enhance logic for formatting regulation amendments and handling affected items.
libs/portals/admin/regulations-admin/src/utils/formatAmendingUtils.ts Introduced several utility functions including groupElementsByArticleTitleFromDiv, extractArticleTitleDisplay, getTextWithSpaces, removeRegPrefix, isGildisTaka, and allSameDay, which assist in processing HTML elements related to regulations.
libs/portals/admin/regulations-admin/src/utils/groupByArticleTitle.ts Removed the groupElementsByArticleTitleFromDiv function, which grouped HTML elements based on the presence of the article__title class.

Possibly related PRs

Suggested reviewers

  • Tryggvig
  • Valur

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 737d9b3 and 4d04dd2.

Files selected for processing (2)
  • libs/portals/admin/regulations-admin/src/utils/formatAmendingRegulation.ts (7 hunks)
  • libs/portals/admin/regulations-admin/src/utils/groupByArticleTitle.ts (1 hunks)
Additional context used
Path-based instructions (2)
libs/portals/admin/regulations-admin/src/utils/formatAmendingRegulation.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/portals/admin/regulations-admin/src/utils/groupByArticleTitle.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 not posted (8)
libs/portals/admin/regulations-admin/src/utils/groupByArticleTitle.ts (2)

Line range hint 1-28: Overall implementation looks good

The function adheres to the coding guidelines for library files:

  • It uses TypeScript for type definitions.
  • It's exported for reuse across different NextJS apps.
  • The implementation doesn't raise any concerns regarding tree-shaking or bundling practices.

9-12: Approved with suggestions for improvement

The addition of the 'chapter__title' class check improves the function's flexibility. However, consider the following suggestions:

  1. Rename the function to better reflect its new behavior, e.g., groupElementsByArticleOrChapterTitleFromDiv.
  2. Add a comment explaining why chapter titles are now included in the grouping logic.
  3. Verify that this change doesn't negatively impact any components or hooks using this function, as it may now group more elements than before.

Here's a suggested refactor incorporating these improvements:

-export const groupElementsByArticleTitleFromDiv = (
+// Groups elements by article or chapter titles to support both regulation structures
+export const groupElementsByArticleOrChapterTitleFromDiv = (
  div: HTMLDivElement,
): HTMLElement[][] => {
  const result: HTMLElement[][] = []
  let currentGroup: HTMLElement[] = []

  Array.from(div.children).forEach((child) => {
    const element = child as HTMLElement
    if (
      element.classList.contains('article__title') ||
      element.classList.contains('chapter__title')
    ) {
      if (currentGroup.length > 0) {
        result.push(currentGroup)
      }
      currentGroup = [element]
    } else {
      currentGroup.push(element)
    }
  })

  if (currentGroup.length > 0) {
    result.push(currentGroup)
  }

  return result
}

To ensure this change doesn't introduce unexpected behavior, run the following script to find all usages of this function:

Review the results to determine if any components need to be updated to handle potential changes in grouping behavior.

Verification successful

Change Verified and Approved

The function groupElementsByArticleTitleFromDiv is used exclusively in formatAmendingRegulation.ts, minimizing the impact of the proposed changes. Proceed with the following improvements:

  1. Rename the function to groupElementsByArticleOrChapterTitleFromDiv to accurately reflect its behavior.
  2. Add a comment explaining the inclusion of chapter titles in the grouping logic.
  3. Update the usage in formatAmendingRegulation.ts accordingly.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of the groupElementsByArticleTitleFromDiv function

rg --type typescript "groupElementsByArticleTitleFromDiv"

Length of output: 92


Script:

#!/bin/bash
# Description: Find all usages of the groupElementsByArticleTitleFromDiv function

rg "groupElementsByArticleTitleFromDiv" --glob "*.ts" --glob "*.tsx"

Length of output: 485

libs/portals/admin/regulations-admin/src/utils/formatAmendingRegulation.ts (6)

11-15: Definition of 'AdditionObject' is appropriate

The introduction of the AdditionObject type enhances type safety and code clarity by formally defining the structure used in the context.


54-54: Optional 'hideAffected' parameter added correctly

The addition of the optional hideAffected parameter to the function signature is well-implemented and maintains backward compatibility.


139-142: Conditional handling of 'joinedAffected' is appropriate

Setting joinedAffected to an empty string when hideAffected is true ensures that affected items are correctly omitted from the output as intended.


205-209: Improved title formatting in repeal logic

The update removes the prefix "reglugerð" and trims whitespace from regTitle, resulting in cleaner and more accurate titles in the generated HTML.


425-427: Regex pattern for previous article title matches as intended

The regular expression /^\d+\. gr\.(?: [a-zA-Z])?(?= |$)/ correctly captures article numbers, optionally followed by a space and a letter, accommodating titles like "12. gr. a".


475-479: Integration of 'allSameDay' function enhances logic flow

Using allSameDay(additions) to determine the hideAffected flag streamlines the decision-making process based on the date consistency of the additions.

Copy link

codecov bot commented Sep 25, 2024

Codecov Report

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

Project coverage is 36.66%. Comparing base (aae6610) to head (922541c).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...regulations-admin/src/utils/formatAmendingUtils.ts 0.00% 45 Missing ⚠️
...ations-admin/src/utils/formatAmendingRegulation.ts 0.00% 9 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16143      +/-   ##
==========================================
+ Coverage   36.64%   36.66%   +0.01%     
==========================================
  Files        6769     6760       -9     
  Lines      139446   138934     -512     
  Branches    39660    39473     -187     
==========================================
- Hits        51100    50934     -166     
+ Misses      88346    88000     -346     
Flag Coverage Δ
api 3.39% <ø> (ø)
application-system-api 41.55% <ø> (ø)
application-template-api-modules 23.62% <ø> (ø)
application-ui-shell 21.29% <ø> (ø)
portals-admin-regulations-admin 1.93% <0.00%> (-0.02%) ⬇️

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

Files with missing lines Coverage Δ
...ations-admin/src/utils/formatAmendingRegulation.ts 0.00% <0.00%> (ø)
...regulations-admin/src/utils/formatAmendingUtils.ts 0.00% <0.00%> (ø)

... and 54 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 aae6610...922541c. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Sep 25, 2024

Datadog Report

All test runs 652d0fb 🔗

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

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.62s 1 no change Link
application-system-api 0 0 0 111 2 2m 58.96s 1 no change Link
application-template-api-modules 0 0 0 109 0 2m 4.22s 1 no change Link
application-ui-shell 0 0 0 74 0 39.91s 1 no change Link
portals-admin-regulations-admin 0 0 0 24 0 15.51s 1 decreased (-0.02%) Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • portals-admin-regulations-admin - jest 2.32% (-0.02%) - Details

Copy link
Member

@thorkellmani thorkellmani left a comment

Choose a reason for hiding this comment

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

Regex seems faulty

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (4)
libs/portals/admin/regulations-admin/src/utils/formatAmendingUtils.ts (4)

32-39: LGTM: Well-implemented title extraction function with room for minor improvement

The extractArticleTitleDisplay function is well-implemented, uses TypeScript correctly, and is reusable. The use of Unicode property escape for matching letters is excellent for internationalization.

A minor suggestion for improved clarity:

Consider adding a comment explaining the regular expression pattern, especially the Unicode property escape \p{L}, as it might not be immediately clear to all developers. For example:

// Matches strings like '1. gr.' or '1. gr. a', where:
// ^\d+\. gr\.   matches the article number and 'gr.' prefix
// (?: [\p{L}])? optionally matches a space followed by any Unicode letter (for sub-articles)
// (?= |$)       ensures the match is followed by a space or the end of the string
const grMatch = title.match(/^\d+\. gr\.(?: [\p{L}])?(?= |$)/u)

64-69: LGTM: Simple and effective prefix removal function

The removeRegPrefix function is well-implemented, uses TypeScript correctly, and is reusable. Its simplicity makes it easy to understand and maintain.

A minor suggestion for improved robustness:

Consider making the prefix check case-insensitive to handle potential variations in capitalization. You can modify the regular expression as follows:

export const removeRegPrefix = (title: string) => {
  return title.replace(/^Reglugerð\s*/i, '');
};

This change will make the function more resilient to variations like "reglugerð" or "REGLUGERÐ", and it also removes any trailing whitespace after the prefix.


71-75: LGTM: Effective regulation check function with room for improvement

The isGildisTaka function is well-implemented, uses TypeScript correctly, and is reusable. It effectively checks for phrases indicating a regulation taking effect.

Suggestions for improved clarity and maintainability:

  1. Add a comment explaining the purpose of the function and the meaning of "GildisTaka".
  2. Consider breaking down the complex regular expression into named parts for better readability. For example:
/**
 * Checks if a string indicates a regulation taking effect (GildisTaka).
 * @param str The string to check
 * @returns True if the string indicates a regulation taking effect, false otherwise
 */
export const isGildisTaka = (str: string): boolean => {
  const takesEffect = /(öðlast|tekur).*gildi/;
  const setWithAuthority = /sett.*með.*(?:heimild|stoð)/;
  const pattern = new RegExp(`${takesEffect.source}|${setWithAuthority.source}`, 'i');
  
  return pattern.test(str || '');
};

This approach makes the function more self-documenting and easier to maintain or extend in the future.


82-89: LGTM: Well-implemented date comparison function with room for minor improvement

The allSameDay function is well-implemented, uses TypeScript correctly, and is reusable. It effectively handles undefined dates and uses the isSameDay function from 'date-fns' for consistent date comparison.

A minor suggestion for improved clarity:

Consider adding a comment explaining the function's behavior when all dates are undefined. Also, you might want to use a more descriptive variable name instead of validObjects. For example:

/**
 * Checks if all provided AdditionObjects have the same date.
 * @param objects Array of AdditionObjects to compare
 * @returns true if all objects have the same date or if all dates are undefined, false otherwise
 */
export const allSameDay = (objects: AdditionObject[]): boolean => {
  const objectsWithDates = objects.filter((obj) => obj.date !== undefined);

  if (objectsWithDates.length === 0) return true; // All dates are undefined
  const firstDate = objectsWithDates[0].date!;

  return objectsWithDates.every((obj) => isSameDay(obj.date!, firstDate));
};

This change improves the function's self-documentation and makes its behavior more explicit.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7d3ae74 and 1ae106e.

📒 Files selected for processing (3)
  • libs/portals/admin/regulations-admin/src/utils/formatAmendingRegulation.ts (7 hunks)
  • libs/portals/admin/regulations-admin/src/utils/formatAmendingUtils.ts (1 hunks)
  • libs/portals/admin/regulations-admin/src/utils/groupByArticleTitle.ts (0 hunks)
💤 Files not reviewed due to no reviewable changes (1)
  • libs/portals/admin/regulations-admin/src/utils/groupByArticleTitle.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/portals/admin/regulations-admin/src/utils/formatAmendingRegulation.ts
🧰 Additional context used
📓 Path-based instructions (1)
libs/portals/admin/regulations-admin/src/utils/formatAmendingUtils.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 not posted (3)
libs/portals/admin/regulations-admin/src/utils/formatAmendingUtils.ts (3)

4-30: LGTM: Well-implemented grouping function

The groupElementsByArticleTitleFromDiv function is well-implemented and adheres to the coding guidelines. It uses TypeScript for type definitions, is reusable across different NextJS apps, and follows efficient practices for DOM manipulation and array operations.


77-80: LGTM: Clear and concise type definition

The AdditionObject type is well-defined, uses TypeScript correctly, and is reusable across different NextJS apps. It clearly specifies the structure of objects representing additions to regulations.


1-89: Overall assessment: Well-implemented utility functions adhering to guidelines

This file provides a set of well-implemented utility functions for processing HTML elements related to regulations. The code adheres to the coding guidelines for files in the libs directory:

  1. Reusability: All functions and types are exported and can be easily used across different NextJS apps.
  2. TypeScript usage: Props and types are consistently defined using TypeScript.
  3. Effective tree-shaking and bundling: The functions are modular and don't have side effects, which should allow for effective tree-shaking.

The code is generally of high quality, with clear and concise implementations. Minor suggestions for improvements have been provided for some functions to enhance clarity, robustness, or performance.

Copy link
Member

@thorkellmani thorkellmani left a comment

Choose a reason for hiding this comment

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

LGTM 🪨

@kodiakhq kodiakhq bot merged commit e5c7467 into main Sep 25, 2024
46 checks passed
@kodiakhq kodiakhq bot deleted the regulations-admin/minor-bugfixing-in-affected branch September 25, 2024 14:04
thoreyjona pushed a commit that referenced this pull request Oct 2, 2024
* Minor affeced bugfixes

* Update after cr comments

* Update article names

---------

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.

2 participants