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(j-s): Date of Birth Validation #17083

Merged
merged 2 commits into from
Nov 28, 2024
Merged

fix(j-s): Date of Birth Validation #17083

merged 2 commits into from
Nov 28, 2024

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Nov 28, 2024

Date of Birth Validation

Hætta að geyma kennitölur með bandstriki í gagnagrunni

What

  • Fixes date of birth validation, allows null values, but non null values must be of the correct format.
  • Sets national id fields in the database to null if no national id is set in the client. This applies to defendants, civil claimants, defenders and spokespersons. Not that previously, the national id was not cleared even if a defender or a spokesperson was saved without a national id. This lead to any previously set national ids to remain in the database and the previous defender not loosing his access. Not a likely scenario but possible.

Why

  • Verified bugs.

Screenshots / Gifs

Screen.Recording.2024-11-28.at.19.38.53.mov

Checklist:

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced nullable handling for nationalId across various components, improving data integrity.
    • Added interfaces for updating lawyer and spokesperson information with nullable fields.
  • Bug Fixes

    • Enhanced validation logic for national IDs in multiple components to ensure proper handling of null values.
  • Refactor

    • Streamlined validation functions for clarity and maintainability.
    • Updated state management for civil claimant data to accommodate nullable national IDs.
  • Documentation

    • Improved handling of input fields to reflect changes in nullable data structures.

@gudjong gudjong requested a review from a team as a code owner November 28, 2024 19:40
Copy link
Contributor

coderabbitai bot commented Nov 28, 2024

Walkthrough

The pull request introduces several changes across various files in the judicial system application. Key modifications include updates to the handling of nullable values for properties such as nationalId, adjustments to validation logic, and refinements in the formatting of messages in the indictment PDF generation. Additionally, new interfaces are introduced for managing lawyer and spokesperson information. Overall, the changes enhance data integrity and validation processes without altering the core functionality of the application.

Changes

File Path Change Summary
apps/judicial-system/backend/src/app/formatters/indictmentPdf.ts Modified createIndictment function to remove unnecessary nullish coalescing operator in formatMessage call for signature section.
apps/judicial-system/backend/src/app/modules/case/case.service.ts Updated UpdateCase interface to change date and explanation fields from nullable to non-nullable. Adjusted handleDateUpdates and handleCommentUpdates methods accordingly.
apps/judicial-system/backend/src/app/transformers/nationalId.transformer.ts Updated Value interface to accept null for value. Modified NationalIdTransformer type to return `string
apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx Introduced LawyerUpdate and SpokespersonUpdate interfaces with nullable fields. Updated logic to set fields to null instead of empty strings.
apps/judicial-system/web/src/components/Inputs/InputNationalId.tsx Adjusted handleBlur function to simplify validation logic for onBlur callback, allowing it to be called under more conditions.
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx Updated handling of nationalId to set it to null instead of an empty string during defendant creation and updating.
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx Modified state type for civilClaimantNationalIdUpdate to allow null for nationalId. Adjusted related functions to handle null values.
apps/judicial-system/web/src/routes/Prosecutor/InvestigationCase/Defendant/Defendant.tsx Updated nationalId assignment to set it to null if undefined or empty during navigation and updates.
apps/judicial-system/web/src/routes/Prosecutor/RestrictionCase/Defendant/Defendant.tsx Altered handleNavigationTo function to assign nationalId conditionally, ensuring it is set to null if falsy.
apps/judicial-system/web/src/routes/Prosecutor/components/DefendantInfo/DefendantInfo.tsx Updated onBlur and onChange event handlers to assign null to nationalId if the input value is empty.
apps/judicial-system/web/src/utils/validate.ts Refactored defendantsAreValid function to use an arrow function. Updated civil claimant validation to utilize the validate function for national ID checks.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • unakb

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

🧹 Outside diff range and nitpick comments (17)
apps/judicial-system/backend/src/app/transformers/nationalId.transformer.ts (1)

7-13: LGTM! Consider adding JSDoc comments

The implementation correctly handles null values while maintaining the existing functionality.

Consider adding JSDoc comments to document the behavior:

+/**
+ * Transforms a national ID by removing hyphens. Preserves null/undefined values.
+ * @param {Object} params - The input parameters
+ * @param {string | null} [params.value] - The national ID value to transform
+ * @returns {string | undefined | null} The transformed national ID, or null/undefined if no value provided
+ */
export const nationalIdTransformer: NationalIdTransformer = ({ value }) => {
apps/judicial-system/web/src/components/Inputs/InputNationalId.tsx (3)

57-61: Convert empty string to null before calling onBlur

While the validation logic is correct, consider converting empty strings to null before calling onBlur to maintain consistency with the PR's objective of setting empty values to null in the database.

-      onBlur(inputValue)
+      onBlur(inputValue || null)

Line range hint 13-21: Enhance component documentation for null value handling

The component's JSDoc comment should be updated to explicitly document how null values are handled, especially for date of birth validation, to align with the PR's objectives.

 /**
  * A reusable input component for national ids. A national id can eiter be a SSN
  * or a date of birth. This component handles input validation for national ids,
- * setting and removing the validation's error message.
+ * setting and removing the validation's error message. When the field is not required,
+ * empty values are treated as null. For date of birth validation, both null values
+ * and properly formatted dates are accepted.
  */

Line range hint 9-12: Strengthen TypeScript types for callback functions

Consider making the types more explicit about null value handling to improve type safety and documentation.

 interface Props extends InputProps {
   isDateOfBirth: boolean
+  onBlur: (value: string | null) => void
+  onChange?: (value: string) => void
 }
apps/judicial-system/backend/src/app/formatters/indictmentPdf.ts (2)

116-122: Consider improving locale-specific string handling

The current implementation has hardcoded string replacements for prosecutor office names. This approach might be problematic for maintenance and internationalization.

Consider extracting these transformations into a configuration file or using a more robust i18n solution:

// prosecutorOfficeTransforms.ts
export const PROSECUTOR_OFFICE_TRANSFORMS = {
  'is-IS': {
    'lögreglustjórinn': 'lögreglustjórans',
    'saksóknari': 'saksóknara'
  }
};

116-122: Add error handling for undefined prosecutor office

The nullish coalescing operator might hide potential data validation issues. Consider adding explicit error handling.

    formatMessage(indictment.signature, {
      prosecutorsOfficeName:
-       lowercase(theCase.prosecutorsOffice?.name)
+       theCase.prosecutorsOffice?.name 
+         ? lowercase(theCase.prosecutorsOffice.name)
            .replace('lögreglustjórinn', 'lögreglustjórans')
            .replace('saksóknari', 'saksóknara')
-         ?? '',
+         : undefined, // Let formatMessage handle the fallback
      date: formatDate(nowFactory(), 'PPP'),
    }),
apps/judicial-system/web/src/routes/Prosecutor/RestrictionCase/Defendant/Defendant.tsx (1)

Line range hint 42-52: Consider adding error handling for updateDefendant operation.

The handleUpdateDefendant function could benefit from proper error handling to manage potential API failures and provide feedback to users.

Consider updating the implementation like this:

  const handleUpdateDefendant = useCallback(
    async (updatedDefendant: UpdateDefendantInput) => {
      updateDefendantState(updatedDefendant)

      if (updatedDefendant.defendantId) {
-       updateDefendant(updatedDefendant)
+       try {
+         await updateDefendant(updatedDefendant)
+       } catch (error) {
+         // Handle error appropriately (e.g., show error message to user)
+         console.error('Failed to update defendant:', error)
+       }
      }
    },
    [updateDefendantState, updateDefendant],
  )
apps/judicial-system/web/src/routes/Prosecutor/components/DefendantInfo/DefendantInfo.tsx (1)

193-193: Consider enhancing type safety for nationalId handling.

While the current implementation works, we could improve type safety by:

  1. Using a custom type for the nationalId field
  2. Adding runtime validation for the null case

Consider this type-safe approach:

type NationalId = string | null;

interface NationalIdProps {
  value: NationalId;
  onChange: (value: NationalId) => void;
  onBlur: (value: NationalId) => void;
}

const validateNationalId = (value: string): NationalId => {
  return value || null;
};

Also applies to: 201-201

apps/judicial-system/web/src/routes/Prosecutor/InvestigationCase/Defendant/Defendant.tsx (1)

Line range hint 97-107: Consider centralizing national ID null handling

To improve maintainability and reduce code duplication, consider extracting the national ID null handling logic into a utility function.

+ const normalizeNationalId = (nationalId?: string) => nationalId || null;
+
  // Then use it in both places:
- nationalId: defendant.nationalId || null,
+ nationalId: normalizeNationalId(defendant.nationalId),
apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx (3)

54-67: LGTM! Consider adding JSDoc comments.

The new interfaces correctly implement nullable fields, aligning with the PR's objective. The structure is clean and well-typed.

Consider adding JSDoc comments to document the purpose of these interfaces:

+/**
+ * Interface for updating lawyer information in the system.
+ * All fields are nullable to handle cases where no information is provided.
+ */
interface LawyerUpdate {
  defenderName: string | null
  defenderNationalId: string | null
  defenderEmail: string | null
  defenderPhoneNumber: string | null
}

+/**
+ * Interface for updating spokesperson information in the system.
+ * All fields are nullable to handle cases where no information is provided.
+ */
interface SpokespersonUpdate {
  spokespersonName: string | null
  spokespersonNationalId: string | null
  spokespersonEmail: string | null
  spokespersonPhoneNumber: string | null
}

Line range hint 140-173: Consider adding null checks for lawyer object properties

While the implementation correctly handles the case when no lawyer is selected, there might be edge cases where the lawyer object exists but contains null values.

Consider adding null checks for the lawyer object properties:

-          defenderName: lawyer ? lawyer.name : label,
-          defenderNationalId: lawyer ? lawyer.nationalId : null,
-          defenderEmail: lawyer ? lawyer.email : null,
-          defenderPhoneNumber: lawyer ? lawyer.phoneNr : null,
+          defenderName: lawyer?.name ?? label,
+          defenderNationalId: lawyer?.nationalId ?? null,
+          defenderEmail: lawyer?.email ?? null,
+          defenderPhoneNumber: lawyer?.phoneNr ?? null,

243-253: Consider refactoring for better maintainability

The current implementation correctly handles null values, but the switch statement could be simplified for better maintainability.

Consider using an object map approach:

-  const formatUpdate = useCallback((property: InputType, value: string) => {
-    switch (property) {
-      case 'defenderEmail': {
-        return {
-          defenderEmail: value || null,
-        }
-      }
-      case 'defenderPhoneNumber': {
-        return { defenderPhoneNumber: value || null }
-      }
-      case 'spokespersonEmail': {
-        return { spokespersonEmail: value || null }
-      }
-      case 'spokespersonPhoneNumber': {
-        return { spokespersonPhoneNumber: value || null }
-      }
-    }
-  }, [])
+  const formatUpdate = useCallback((property: InputType, value: string) => {
+    const updateMap: Record<InputType, string> = {
+      defenderEmail: 'defenderEmail',
+      defenderPhoneNumber: 'defenderPhoneNumber',
+      spokespersonEmail: 'spokespersonEmail',
+      spokespersonPhoneNumber: 'spokespersonPhoneNumber'
+    }
+    return { [updateMap[property]]: value || null }
+  }, [])
apps/judicial-system/web/src/utils/validate.ts (2)

265-267: Consider simplifying the validation logic.

The current implementation can be made more concise while maintaining readability.

-  const defendantsAreValid = workingCase.defendants?.every(
-    (defendant) => validate([[defendant.defendantPlea, ['empty']]]).isValid,
-  )
+  const defendantsAreValid = workingCase.defendants?.every((defendant) =>
+    validate([[defendant.defendantPlea, ['empty']]]).isValid
+  )

Line range hint 1-1: Address the TODO comment regarding missing tests.

Given the critical nature of validation logic in a judicial system, comprehensive test coverage is essential. Would you like me to help generate test cases for these validation functions?

apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (1)

190-197: Consider adding validation for date of birth format.

Since this PR focuses on date of birth validation, consider adding explicit format validation when noNationalId is true, as the field would then represent a date of birth.

 if (noNationalId) {
+  // Validate date format when field represents date of birth
+  const isValidDateFormat = /^\d{2}\.\d{2}\.\d{4}$/.test(nationalId);
+  if (nationalId && !isValidDateFormat) {
+    return;
+  }
   handleUpdateCivilClaimant({
     caseId: workingCase.id,
     civilClaimantId,
     nationalId: nationalId || null,
   })
 }
apps/judicial-system/backend/src/app/modules/case/case.service.ts (2)

189-192: Consider adding JSDoc documentation and validation constraints.

While the type definitions are correct, consider the following improvements:

  1. Add JSDoc documentation to describe the purpose and expected format of each field
  2. Consider adding validation constraints for postponedIndefinitelyExplanation and civilDemands fields

Example documentation:

+ /** Date and location for arraignment */
  arraignmentDate?: UpdateDateLog
+ /** Date and location for court hearing */
  courtDate?: UpdateDateLog
+ /** Explanation for indefinite postponement of the case */
  postponedIndefinitelyExplanation?: string
+ /** Civil demands associated with the case */
  civilDemands?: string

Line range hint 516-607: Consider refactoring to reduce code duplication between date and comment update handlers.

The handleDateUpdates and handleCommentUpdates methods share similar patterns. Consider extracting the common logic into a generic handler to improve maintainability.

Example refactor:

interface UpdateHandler<T, K extends keyof UpdateCase> {
  model: any;
  types: Record<K, T>;
  getWhere: (caseId: string, type: T) => object;
  getValue: (update: any) => any;
}

private async handleUpdates<T, K extends keyof UpdateCase>(
  theCase: Case,
  update: UpdateCase,
  handler: UpdateHandler<T, K>,
  transaction: Transaction
) {
  for (const key in handler.types) {
    const updateValue = update[key as K];
    if (updateValue !== undefined) {
      const type = handler.types[key as K];
      const where = handler.getWhere(theCase.id, type);
      
      const existing = await handler.model.findOne({ where, transaction });
      
      if (existing) {
        if (updateValue === null) {
          await handler.model.destroy({ where, transaction });
        } else {
          await handler.model.update(
            handler.getValue(updateValue),
            { where, transaction }
          );
        }
      } else if (updateValue !== null) {
        await handler.model.create(
          { caseId: theCase.id, ...handler.getValue(updateValue), type },
          { transaction }
        );
      }
      
      delete update[key as K];
    }
  }
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0de2db5 and 1854970.

📒 Files selected for processing (11)
  • apps/judicial-system/backend/src/app/formatters/indictmentPdf.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/transformers/nationalId.transformer.ts (1 hunks)
  • apps/judicial-system/web/src/components/Inputs/InputAdvocate.tsx (4 hunks)
  • apps/judicial-system/web/src/components/Inputs/InputNationalId.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx (4 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (2 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/InvestigationCase/Defendant/Defendant.tsx (2 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/RestrictionCase/Defendant/Defendant.tsx (1 hunks)
  • apps/judicial-system/web/src/routes/Prosecutor/components/DefendantInfo/DefendantInfo.tsx (1 hunks)
  • apps/judicial-system/web/src/utils/validate.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
apps/judicial-system/backend/src/app/formatters/indictmentPdf.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/judicial-system/backend/src/app/modules/case/case.service.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/judicial-system/backend/src/app/transformers/nationalId.transformer.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/judicial-system/web/src/components/Inputs/InputAdvocate.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/judicial-system/web/src/components/Inputs/InputNationalId.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/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.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/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.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/judicial-system/web/src/routes/Prosecutor/InvestigationCase/Defendant/Defendant.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/judicial-system/web/src/routes/Prosecutor/RestrictionCase/Defendant/Defendant.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/judicial-system/web/src/routes/Prosecutor/components/DefendantInfo/DefendantInfo.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/judicial-system/web/src/utils/validate.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."
📓 Learnings (3)
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx (2)
Learnt from: gudjong
PR: island-is/island.is#16863
File: apps/judicial-system/web/src/routes/Prosecutor/Indictments/Overview/Overview.tsx:194-200
Timestamp: 2024-11-27T14:34:38.028Z
Learning: In `Overview.tsx`, the `defendant.subpoenas` array never contains null or undefined `subpoena` objects, so additional null checks are not needed.
Learnt from: oddsson
PR: island-is/island.is#16731
File: apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx:172-186
Timestamp: 2024-11-12T15:15:20.157Z
Learning: In `IndictmentOverview.tsx`, since the defendants data does not change, using `useMemo` to memoize the filtering logic is unnecessary.
apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (1)
Learnt from: gudjong
PR: island-is/island.is#15421
File: apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx:55-61
Timestamp: 2024-11-12T15:15:11.835Z
Learning: The `updateCase` method in the `apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx` file has its own error handling, and additional error handling in the `initialize` function is not necessary.
apps/judicial-system/web/src/routes/Prosecutor/InvestigationCase/Defendant/Defendant.tsx (1)
Learnt from: oddsson
PR: island-is/island.is#16831
File: apps/judicial-system/backend/src/app/modules/defendant/models/defendant.model.ts:0-0
Timestamp: 2024-11-19T09:04:44.520Z
Learning: Additional documentation is not required when the code is clear and self-explanatory.
🔇 Additional comments (12)
apps/judicial-system/backend/src/app/transformers/nationalId.transformer.ts (1)

1-5: Verify the impact of breaking type changes

The type changes correctly implement null handling as per requirements. However, since this is a breaking change, we should verify all consumers of this transformer.

✅ Verification successful

Breaking type changes are safe to proceed

The type changes in the nationalId.transformer are safe because:

  • All usages are in DTO classes where the nationalId fields are already marked as optional (?)
  • The transformer is consistently used with @Transform() decorator in combination with @ApiPropertyOptional
  • All consuming DTOs properly handle the nullable/optional nature of the fields

The changes align with the existing codebase patterns and won't cause runtime issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of nationalIdTransformer to verify they handle null values correctly
# Search for imports and usages
rg -A 3 "nationalIdTransformer" --type typescript

Length of output: 84


Script:

#!/bin/bash
# Search for nationalIdTransformer using ripgrep without file type restriction
rg -l "nationalIdTransformer"

# Get content of files containing nationalIdTransformer
rg -A 3 "nationalIdTransformer"

Length of output: 13339

apps/judicial-system/backend/src/app/formatters/indictmentPdf.ts (1)

116-122: Verify string replacement logic

Let's verify that these string replacements cover all possible prosecutor office name formats.

✅ Verification successful

Let me analyze the search results to verify the string replacement logic for prosecutor office names.

From the search results, I can see that there are several variations of prosecutor office names in the codebase:

  1. Names starting with "Lögreglustjórinn":

    • Lögreglustjórinn á höfuðborgarsvæðinu
    • Lögreglustjórinn á Suðurnesjum
    • Lögreglustjórinn á Norðurl vest
  2. Names ending with "saksóknari":

    • Héraðssaksóknari
    • Ríkissaksóknari
    • Aðalsaksóknari

Looking at the code in indictmentPdf.ts:

.replace('lögreglustjórinn', 'lögreglustjórans')
.replace('saksóknari', 'saksóknara')

The replacements are correct and handle both patterns:

  1. Converting "lögreglustjórinn" to "lögreglustjórans" for police offices
  2. Converting "saksóknari" to "saksóknara" for prosecutor offices

This is also consistent with the transformation logic used in other parts of the codebase, as seen in apps/judicial-system/web/src/routes/Prosecutor/InvestigationCase/PoliceDemands/PoliceDemands.tsx.

String replacement logic is correctly implemented

The current implementation handles all prosecutor office name formats found in the codebase. The transformations are consistent with Icelandic grammar rules for the genitive case.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for prosecutor office names in the codebase to ensure all formats are handled

# Search for prosecutor office related strings
rg -i "lögreglustjóri|saksóknar" --type ts

# Search for test cases related to prosecutor office name formatting
rg -i "test.*prosecutor.*office|test.*lögreglustjóri" --type ts

Length of output: 18794

apps/judicial-system/web/src/routes/Prosecutor/RestrictionCase/Defendant/Defendant.tsx (1)

110-110: LGTM! Proper handling of null nationalId.

The change correctly implements the requirement to set nationalId to null when no value is provided, aligning with the PR's objective to fix national ID handling.

Let's verify the consistent handling of nationalId across related components:

✅ Verification successful

Consistent handling of null nationalId confirmed

The code correctly handles the case where a defendant's nationalId is undefined by explicitly setting it to null, which aligns with the PR's objective. The context shows that:

  1. The nationalId assignment is part of a larger defendant data structure
  2. The code uses the nullish coalescing operator (||) to ensure null is set when nationalId is undefined
  3. This handling is consistent with the component's structure where other defendant properties are managed similarly
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent nationalId handling in related components
# Expected: All components should handle nationalId similarly by allowing null values

# Search for nationalId assignments in defendant-related components
ast-grep --pattern 'nationalId: $_'

# Search for potential inconsistencies in nationalId handling
rg -A 3 'nationalId(?!.*null)'

Length of output: 3769


Script:

#!/bin/bash
# Let's try a different approach to find nationalId handling patterns
# Search for nationalId assignments in TypeScript/JavaScript files
rg -t ts -t js "nationalId.*=" -A 2

# Search for type definitions related to nationalId
ast-grep --pattern "nationalId?: $_"

# Search for nationalId in interfaces and types
ast-grep --pattern "interface $_ {
  $$$
  nationalId: $_
  $$$
}"

Length of output: 101008


Script:

#!/bin/bash
# Let's search specifically in the judicial system app for nationalId handling
rg -t ts -t tsx "nationalId" apps/judicial-system/

# Search for type definitions of defendants in the judicial system
ast-grep --pattern "interface $_ {
  $$$
  defendants: $_
  $$$
}"

# Search for defendant-related interfaces
ast-grep --pattern "interface Defendant {
  $$$
  nationalId: $_
  $$$
}"

Length of output: 360


Script:

#!/bin/bash
# Fix the file type and path issues in the previous search
rg -t typescript -t tsx "nationalId" apps/judicial-system/web/src/

# Look for defendant type definitions
ast-grep --pattern "type Defendant = {
  $$$
  nationalId: $_
  $$$
}"

# Search for defendant-related code in the specific file
rg -A 3 "defendants\[0\]" apps/judicial-system/web/src/routes/Prosecutor/RestrictionCase/Defendant/Defendant.tsx

Length of output: 1013

apps/judicial-system/web/src/routes/Prosecutor/components/DefendantInfo/DefendantInfo.tsx (1)

193-193: LGTM! Verify null handling consistency.

The change to use null instead of empty strings for missing national IDs is correct and aligns with the PR objectives. This ensures proper database state when no national ID is provided.

Let's verify the null handling consistency across the codebase:

Also applies to: 201-201

✅ Verification successful

Null handling for nationalId is consistent with the codebase

Based on the search results, the change to handle empty nationalId values as null is consistent with the codebase's patterns. The evidence shows:

  1. The Defendant interface in the judicial system allows for optional nationalId (marked with ?)
  2. The codebase consistently handles cases where nationalId might be null or undefined through:
    • Null checks before using the value
    • Conditional rendering based on nationalId presence
    • Format utilities that handle null/undefined cases
  3. The change aligns with the existing validation logic that checks for both empty and null cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent null handling in national ID fields
# Look for other instances where nationalId is handled to ensure consistent null handling

# Search for nationalId assignments
rg -A 2 "nationalId:?\s*[^,}]*" --type typescript

# Search for database schema definitions related to nationalId
rg -A 5 "nationalId.*:.*" --type graphql

Length of output: 161


Script:

#!/bin/bash
# Let's try with ripgrep without file type filters
# Search for nationalId assignments and related patterns
rg -i "nationalId.*[:=]" -A 2

# Search for schema or type definitions
rg -i "nationalId.*:" --glob "*.{ts,tsx,graphql,gql}"

# Search for specific handling of national ID in forms or components
rg -i "nationalId" --glob "*.tsx" -A 3

Length of output: 131140


Script:

#!/bin/bash
# Let's search specifically for nationalId handling in the DefendantInfo component and related files
rg -A 3 "nationalId.*=.*null" --glob "apps/judicial-system/web/src/**/*.{ts,tsx}"

# Look for type definitions and interfaces related to defendant info
rg -A 3 "interface.*Defendant" --glob "apps/judicial-system/**/*.{ts,tsx}"

# Search for other instances of null handling in defendant-related code
rg -A 3 "defendant.*nationalId" --glob "apps/judicial-system/**/*.{ts,tsx}"

Length of output: 44040

apps/judicial-system/web/src/routes/Prosecutor/InvestigationCase/Defendant/Defendant.tsx (2)

97-97: LGTM: Proper handling of null national IDs

The change correctly implements the nullish coalescing operator to ensure that empty or undefined national IDs are properly converted to null, preventing the issue where previous defenders could retain access.


107-107: LGTM: Consistent null handling for new defendants

The change maintains consistency with the updateDefendant implementation, ensuring that new defendants are also created with proper null handling for national IDs.

apps/judicial-system/web/src/utils/validate.ts (2)

277-284: LGTM! Validation logic aligns with requirements.

The implementation correctly handles both national ID and date of birth validation, allowing for null values when noNationalId is true. This aligns with the PR objective to fix date of birth validation.


293-293: LGTM! Clean and readable code.

The simplified reference to defendantsAreValid improves code readability.

apps/judicial-system/web/src/routes/Prosecutor/Indictments/Defendant/Defendant.tsx (2)

Line range hint 354-366: LGTM! Consistent handling of null national IDs during navigation.

The changes ensure that empty national IDs are properly set to null instead of empty strings, which aligns with the database requirements and prevents issues with previous defenders retaining access.


Line range hint 424-447: LGTM! Consistent handling of null national IDs during defendant creation.

The changes maintain consistency by initializing national IDs as null in both the temporary and persisted states of new defendants.

apps/judicial-system/web/src/routes/Prosecutor/Indictments/Processing/Processing.tsx (2)

78-78: LGTM! Type definition properly handles nullable national IDs.

The updated type definition aligns with the PR objectives by explicitly handling cases where national IDs may be null. This change improves type safety and better represents the actual data model.


190-190: Verify the impact of null national IDs on the database.

The changes correctly implement null handling for national IDs, but let's verify that this doesn't affect any existing queries or validations.

Also applies to: 195-195

✅ Verification successful

Null national IDs are safely handled in the codebase

Based on the validation code found in the judicial system, the nationalId field is properly validated with specific rules that account for both null and non-null cases. The validation logic explicitly handles cases where noNationalId is true by switching to date-of-birth validation instead of national ID validation. This confirms that the database impact of null national IDs has been considered in the system's validation layer.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential issues with null national ID handling in queries and validations

# Search for GraphQL queries/mutations handling nationalId
rg -l "nationalId.*null" --type ts

# Look for validation logic related to national IDs
ast-grep --pattern 'nationalId.*validate' 

# Check for database schema definitions
fd "schema|model" --type ts --exec rg -l "nationalId"

Length of output: 4421


Script:

#!/bin/bash
# Let's check for GraphQL schema definitions and database models specifically
rg -l "nationalId.*type.*" --type typescript

# Check for validation logic in the judicial system
rg -l "nationalId.*validate" --type typescript apps/judicial-system/

# Look for GraphQL mutations in the judicial system
ast-grep --pattern 'mutation {
  $$$
  nationalId
  $$$
}'

# Check database models and types in the judicial system
rg -A 5 "nationalId" apps/judicial-system/backend/src/app/modules/models/

Length of output: 415


Script:

#!/bin/bash
# Let's try with correct file type flags and paths
# Check for GraphQL schema definitions and database models
rg -l "nationalId.*type" --type ts

# Check for validation logic in the judicial system
rg -A 5 "nationalId" apps/judicial-system/web/src/utils/validate.ts

# Look for GraphQL mutations and types in the judicial system
rg -A 5 "nationalId" apps/judicial-system/web/src/types/
rg -A 5 "nationalId" apps/judicial-system/web/src/utils/mutations.ts

# Check for database models in the judicial system
rg -A 5 "nationalId" apps/judicial-system/shared/src/models/

Length of output: 2431

Copy link

codecov bot commented Nov 28, 2024

Codecov Report

Attention: Patch coverage is 5.40541% with 35 lines in your changes missing coverage. Please review.

Project coverage is 35.68%. Comparing base (0de2db5) to head (958a1ad).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...system/web/src/components/Inputs/InputAdvocate.tsx 0.00% 12 Missing ⚠️
apps/judicial-system/web/src/utils/validate.ts 16.66% 5 Missing ⚠️
...end/src/app/transformers/nationalId.transformer.ts 25.00% 3 Missing ⚠️
...stem/web/src/components/Inputs/InputNationalId.tsx 0.00% 3 Missing ⚠️
...s/Prosecutor/Indictments/Processing/Processing.tsx 0.00% 3 Missing ⚠️
...system/backend/src/app/formatters/indictmentPdf.ts 0.00% 2 Missing ⚠️
...tes/Prosecutor/Indictments/Defendant/Defendant.tsx 0.00% 2 Missing ⚠️
...osecutor/InvestigationCase/Defendant/Defendant.tsx 0.00% 2 Missing ⚠️
...secutor/components/DefendantInfo/DefendantInfo.tsx 0.00% 2 Missing ⚠️
...Prosecutor/RestrictionCase/Defendant/Defendant.tsx 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #17083      +/-   ##
==========================================
- Coverage   35.68%   35.68%   -0.01%     
==========================================
  Files        6941     6941              
  Lines      147218   147227       +9     
  Branches    41849    41941      +92     
==========================================
  Hits        52538    52538              
- Misses      94680    94689       +9     
Flag Coverage Δ
air-discount-scheme-web 0.00% <ø> (ø)
api 3.34% <ø> (ø)
api-domains-auth-admin 48.49% <ø> (ø)
api-domains-communications 39.53% <ø> (ø)
application-api-files 62.14% <ø> (ø)
application-core 70.91% <ø> (+0.31%) ⬆️
application-system-api 38.73% <ø> (ø)
application-template-api-modules 27.79% <ø> (+0.01%) ⬆️
application-templates-accident-notification 28.97% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 25.86% <ø> (ø)
application-templates-driving-license 18.18% <ø> (ø)
application-templates-estate 13.75% <ø> (ø)
application-templates-example-payment 24.80% <ø> (ø)
application-templates-financial-aid 15.80% <ø> (ø)
application-templates-general-petition 23.09% <ø> (ø)
application-templates-inheritance-report 6.58% <ø> (ø)
application-templates-marriage-conditions 15.12% <ø> (ø)
application-templates-mortgage-certificate 43.27% <ø> (ø)
application-templates-parental-leave 29.93% <ø> (ø)
application-types 6.51% <ø> (ø)
application-ui-components 1.27% <ø> (ø)
application-ui-shell 21.44% <ø> (ø)
auth-react 24.40% <ø> (ø)
clients-charge-fjs-v2 24.11% <ø> (ø)
clients-regulations 42.40% <ø> (ø)
cms 0.40% <ø> (ø)
cms-translations 38.86% <ø> (ø)
content-search-toolkit 8.20% <ø> (ø)
contentful-apps 4.74% <ø> (ø)
financial-aid-backend 51.30% <ø> (ø)
financial-aid-shared 17.81% <ø> (ø)
island-ui-core 30.94% <ø> (ø)
judicial-system-api 20.36% <ø> (ø)
judicial-system-backend 55.65% <16.66%> (ø)
judicial-system-web 28.00% <3.22%> (-0.02%) ⬇️
portals-admin-regulations-admin 1.80% <ø> (ø)
portals-core 18.38% <ø> (ø)
regulations 16.78% <ø> (ø)
services-user-notification 46.66% <ø> (-0.04%) ⬇️
shared-components 29.13% <ø> (ø)
shared-form-fields 33.88% <ø> (ø)
web 2.44% <ø> (ø)

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

Files with missing lines Coverage Δ
...ystem/backend/src/app/modules/case/case.service.ts 90.75% <ø> (ø)
...Prosecutor/RestrictionCase/Defendant/Defendant.tsx 0.00% <0.00%> (ø)
...system/backend/src/app/formatters/indictmentPdf.ts 16.98% <0.00%> (+0.61%) ⬆️
...tes/Prosecutor/Indictments/Defendant/Defendant.tsx 0.00% <0.00%> (ø)
...osecutor/InvestigationCase/Defendant/Defendant.tsx 0.00% <0.00%> (ø)
...secutor/components/DefendantInfo/DefendantInfo.tsx 1.42% <0.00%> (-0.05%) ⬇️
...end/src/app/transformers/nationalId.transformer.ts 25.00% <25.00%> (-25.00%) ⬇️
...stem/web/src/components/Inputs/InputNationalId.tsx 3.22% <0.00%> (ø)
...s/Prosecutor/Indictments/Processing/Processing.tsx 0.00% <0.00%> (ø)
apps/judicial-system/web/src/utils/validate.ts 40.85% <16.66%> (+0.15%) ⬆️
... and 1 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 0de2db5...958a1ad. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 28, 2024

Datadog Report

All test runs 4d0fb8a 🔗

43 Total Test Services: 0 Failed, 39 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.01%), 2 increased, 182 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
air-discount-scheme-web 0 0 0 2 0 7.15s 1 no change Link
api 0 0 0 4 0 2.53s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 10.35s 1 no change Link
api-domains-communications 0 0 0 5 0 30.58s 1 no change Link
api-domains-license-service 0 0 0 0 0 481.7ms 1 no change Link
application-api-files 0 0 0 2 0 4.26s 1 no change Link
application-core 0 0 0 97 0 14.93s 1 increased (+0.2%) Link
application-system-api 0 0 0 40 0 2m 22.35s 1 no change Link
application-template-api-modules 0 0 0 118 0 2m 5.78s 1 no change Link
application-templates-accident-notification 0 0 0 148 0 15.86s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • services-user-notification - jest 69.16% (-0.01%) - Details

@oddsson oddsson added the automerge Merge this PR as soon as all checks pass label Nov 28, 2024
@kodiakhq kodiakhq bot merged commit 253bfe7 into main Nov 28, 2024
149 checks passed
@kodiakhq kodiakhq bot deleted the j-s/national-id-format-fix branch November 28, 2024 21:58
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