Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(j-s): Civil Claimant Spokesperson Access #16389

Merged
merged 20 commits into from
Oct 18, 2024
Merged

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Oct 14, 2024

Civil Claimant Spokesperson Access

Bótakrafa - aðgangur réttargæslumanns/lögmanns kröfuhafa að réttarvörslugáttinni
Verjandi á ekki að geta bætt við gögnum þegar máli er lokið

What

  • Allows civil claimants spokespersons to log in as defenders.
  • Shows defenders cases where they are assigned as spokespersons to civil claimants.
  • Blocks spokesperson access to case files and generated PDFs unless they are granted a special permission.
  • Hides the button to add documents after a case is completed. Also hides this button from spokespersons.

Why

  • Civil claimant spokespersons need access.

Screenshots / Gifs

Screen.Recording.2024-10-16.at.10.08.01.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

  • New Features

    • Enhanced access control for various user roles, including new functions to manage permissions for viewing case files.
    • Introduced a method to find claimants by spokesperson national ID in the CivilClaimantService.
    • Updated the LimitedAccessViewCaseFileGuard to improve access control logic for case file permissions.
  • Bug Fixes

    • Improved logic for retrieving cases associated with defense users.
  • Documentation

    • Updated test cases to reflect changes in filtering logic and access control.
  • Refactor

    • Restructured methods for better readability and flow in the authorization process.

Copy link

codecov bot commented Oct 14, 2024

Codecov Report

Attention: Patch coverage is 78.43137% with 33 lines in your changes missing coverage. Please review.

Project coverage is 36.75%. Comparing base (3552edc) to head (2ae490a).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...s/Shared/IndictmentOverview/IndictmentOverview.tsx 0.00% 13 Missing ⚠️
.../backend/src/app/modules/case/guards/rolesRules.ts 16.66% 10 Missing ⚠️
...system/api/src/app/modules/auth/auth.controller.ts 0.00% 4 Missing ⚠️
...src/app/modules/defendant/civilClaimant.service.ts 66.66% 2 Missing ⚠️
...ackend/src/app/modules/case/filters/case.filter.ts 96.96% 1 Missing ⚠️
.../interceptors/limitedAccessCaseFile.interceptor.ts 50.00% 1 Missing ⚠️
.../src/app/modules/case/limitedAccessCase.service.ts 88.88% 1 Missing ⚠️
...nd/src/app/modules/file/guards/caseFileCategory.ts 97.43% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16389      +/-   ##
==========================================
- Coverage   36.75%   36.75%   -0.01%     
==========================================
  Files        6835     6835              
  Lines      141332   141421      +89     
  Branches    40240    40327      +87     
==========================================
+ Hits        51949    51977      +28     
- Misses      89383    89444      +61     
Flag Coverage Δ
air-discount-scheme-backend 54.08% <ø> (ø)
air-discount-scheme-web 0.00% <ø> (ø)
api 3.37% <ø> (ø)
api-domains-air-discount-scheme 36.93% <ø> (ø)
api-domains-assets 26.71% <ø> (ø)
api-domains-auth-admin 48.48% <ø> (ø)
api-domains-communications 39.90% <ø> (ø)
api-domains-criminal-record 48.00% <ø> (ø)
api-domains-driving-license 44.43% <ø> (ø)
api-domains-education 31.58% <ø> (ø)
api-domains-health-insurance 34.77% <ø> (ø)
api-domains-mortgage-certificate 34.95% <ø> (ø)
api-domains-payment-schedule 41.16% <ø> (ø)
application-api-files 56.86% <ø> (ø)
application-core 71.64% <ø> (+0.40%) ⬆️
application-system-api 41.37% <ø> (ø)
application-template-api-modules 27.83% <ø> (-0.02%) ⬇️
application-templates-accident-notification 29.27% <ø> (ø)
application-templates-car-recycling 3.12% <ø> (ø)
application-templates-criminal-record 26.34% <ø> (ø)
application-templates-driving-license 18.32% <ø> (ø)
application-templates-estate 12.32% <ø> (ø)
application-templates-example-payment 25.14% <ø> (ø)
application-templates-financial-aid 15.50% <ø> (ø)
application-templates-general-petition 23.44% <ø> (ø)
application-templates-inheritance-report 6.49% <ø> (ø)
application-templates-marriage-conditions 15.17% <ø> (ø)
application-templates-mortgage-certificate 43.82% <ø> (ø)
application-templates-parental-leave 29.96% <ø> (ø)
application-types 6.63% <ø> (ø)
application-ui-components 1.28% <ø> (ø)
application-ui-shell 21.37% <ø> (ø)
auth-react 22.77% <ø> (ø)
clients-charge-fjs-v2 24.11% <ø> (ø)
clients-driving-license 40.67% <ø> (ø)
clients-driving-license-book 43.80% <ø> (ø)
clients-financial-statements-inao 49.32% <ø> (ø)
clients-license-client 1.83% <ø> (ø)
clients-middlewares 72.84% <ø> (ø)
clients-regulations 42.80% <ø> (ø)
clients-rsk-company-registry 29.76% <ø> (ø)
clients-syslumenn 49.44% <ø> (ø)
cms 0.42% <ø> (ø)
cms-translations 39.03% <ø> (ø)
contentful-apps 5.44% <ø> (ø)
download-service 44.22% <ø> (ø)
financial-aid-backend 56.37% <ø> (ø)
financial-aid-shared 18.94% <ø> (ø)
island-ui-core 28.39% <ø> (ø)
judicial-system-api 18.37% <0.00%> (+<0.01%) ⬆️
judicial-system-backend 55.29% <87.50%> (+0.13%) ⬆️
judicial-system-web 27.91% <38.09%> (-0.01%) ⬇️
license-api 42.69% <ø> (ø)
nest-aws ?
portals-admin-regulations-admin 1.85% <ø> (ø)
portals-core 16.15% <ø> (ø)
services-auth-admin-api 51.93% <ø> (ø)
services-auth-delegation-api 57.30% <ø> (-0.07%) ⬇️
services-auth-ids-api 51.42% <ø> (ø)
services-auth-personal-representative 45.10% <ø> (-0.04%) ⬇️
services-auth-personal-representative-public 41.22% <ø> (-0.04%) ⬇️
services-auth-public-api 48.90% <ø> (ø)
services-endorsements-api 53.66% <ø> (ø)
services-university-gateway 48.28% <ø> (-0.09%) ⬇️
services-user-notification 47.02% <ø> (+0.02%) ⬆️
services-user-profile 62.19% <ø> (+0.16%) ⬆️
shared-components 27.65% <ø> (ø)
shared-form-fields 31.59% <ø> (ø)
shared-utils 27.69% <ø> (ø)
web 1.82% <ø> (ø)

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

Files with missing lines Coverage Δ
...ckend/src/app/modules/case/filters/cases.filter.ts 97.91% <ø> (ø)
...icial-system/backend/src/app/modules/case/index.ts 100.00% <100.00%> (ø)
...c/app/modules/case/limitedAccessCase.controller.ts 97.61% <100.00%> (ø)
...c/app/modules/case/test/createTestingCaseModule.ts 100.00% <100.00%> (ø)
...kend/src/app/modules/defendant/defendant.module.ts 0.00% <ø> (ø)
...end/src/app/modules/defendant/defendant.service.ts 82.55% <ø> (ø)
...-system/backend/src/app/modules/defendant/index.ts 100.00% <100.00%> (ø)
...pp/modules/defendant/models/civilClaimant.model.ts 93.93% <100.00%> (+3.93%) ⬆️
...rc/app/modules/defendant/models/defendant.model.ts 87.50% <100.00%> (+1.78%) ⬆️
...les/file/guards/limitedAccessViewCaseFile.guard.ts 100.00% <100.00%> (ø)
... and 11 more

... and 2 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 3552edc...2ae490a. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 14, 2024

Datadog Report

All test runs 543b1f7 🔗

68 Total Test Services: 0 Failed, 65 Passed
🔻 Test Sessions change in coverage: 2 decreased, 3 increased, 195 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-backend 0 0 0 81 0 31.9s N/A Link
air-discount-scheme-web 0 0 0 2 0 7.71s N/A Link
api 0 0 0 4 0 2.56s N/A Link
api-domains-air-discount-scheme 0 0 0 6 0 17.15s N/A Link
api-domains-assets 0 0 0 3 0 11.04s N/A Link
api-domains-auth-admin 0 0 0 18 0 12.2s N/A Link
api-domains-communications 0 0 0 5 0 27.11s N/A Link
api-domains-criminal-record 0 0 0 5 0 8.82s 1 no change Link
api-domains-driving-license 0 0 0 23 0 30.56s N/A Link
api-domains-education 0 0 0 8 0 20.42s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (2)

  • services-auth-delegation-api - jest 51.22% (-0.19%) - Details
  • services-university-gateway - jest 44.84% (-0.02%) - Details

@gudjong gudjong marked this pull request as ready for review October 16, 2024 10:12
@gudjong gudjong requested a review from a team as a code owner October 16, 2024 10:12
Copy link
Contributor

coderabbitai bot commented Oct 16, 2024

Walkthrough

The pull request introduces modifications across various modules of the judicial system application. Key changes include restructuring access control logic, enhancing user role management, and updating related tests. The AuthController's authorizeUser method has been streamlined, while multiple filtering and guard functions have been refined to improve permission checks for different user roles. Additionally, components in the web interface are updated to support new props for conditional rendering, reflecting the enhanced access control logic.

Changes

File Path Change Summary
apps/judicial-system/api/src/app/modules/auth/auth.controller.ts Restructured authorizeUser method to find a defender regardless of user presence; adjusted indentation for readability.
apps/judicial-system/backend/src/app/modules/case/filters/case.filter.ts Updated canDefenceUserAccessCase to declare forUpdate as boolean; split into three functions for granular access checks.
apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts Modified getDefenceUserCasesQueryFilter to broaden criteria for retrieving cases.
apps/judicial-system/backend/src/app/modules/case/filters/test/*.spec.ts Updated test cases to reflect changes in filtering logic; clarified variable names and added new test cases.
apps/judicial-system/backend/src/app/modules/case/guards/rolesRules.ts Introduced defenderGeneratedPdfRule for managing access to generated PDFs.
apps/judicial-system/backend/src/app/modules/case/index.ts Updated to export defenderGeneratedPdfRule.
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts Updated to integrate new access rules related to civil claimants.
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts Enhanced functionality related to civil claimants; included CivilClaimantService.
apps/judicial-system/backend/src/app/modules/defendant/*.ts Added methods for finding claimants and updated DefendantService to normalize national IDs; added static methods to models for checking relationships.
apps/judicial-system/backend/src/app/modules/file/guards/*.ts Updated case file category management and LimitedAccessViewCaseFileGuard for enhanced access control logic; added new permission-checking functions.
apps/judicial-system/backend/src/app/modules/subpoena/limitedAccessSubpoena.controller.ts Replaced defenderRule with defenderGeneratedPdfRule in access control logic.
apps/judicial-system/web/src/components/IndictmentCaseFilesList/IndictmentCaseFilesList.tsx Added optional prop displayGeneratedPDFs for conditional rendering of generated PDFs.
apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx Enhanced user permission logic with national ID checks for rendering case files.

Suggested labels

automerge

Possibly related PRs


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a4a3160 and 3575125.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/defendant/models/defendant.model.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/judicial-system/backend/src/app/modules/defendant/models/defendant.model.ts
🧰 Additional context used
📓 Learnings (1)
📓 Common learnings
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts:1-1
Timestamp: 2024-10-17T11:30:12.482Z
Learning: The usage of `defenderRule` in the following test files is intentional and should remain unchanged:

- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createPresignedPostRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/deleteCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/getCaseFileSignedUrlRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRulingPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRequestPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCourtRecordPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getByIdRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getAllFilesZipRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/caseController/getAllRolesRules.spec.ts`

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.

coderabbitai[bot]
coderabbitai bot previously requested changes Oct 16, 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: 17

🧹 Outside diff range and nitpick comments (27)
apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getIndictmentPdfRolesRules.spec.ts (2)

17-17: LGTM! Consider expanding test coverage.

The update to use defenderGeneratedPdfRule in the expectation check is consistent with the import statement change. This maintains the test's integrity while reflecting the new, more specific rule.

Consider adding more test cases to cover different scenarios, such as:

  1. Verifying that other roles don't have access to the generated PDF.
  2. Testing the behavior when the rule is not present.

This would enhance the robustness of your test suite.


Line range hint 1-19: Enhance test coverage for comprehensive validation.

While the current test structure is clear and follows Jest best practices, consider expanding the test suite to cover more scenarios related to the PR objectives:

  1. Add tests for different user roles (e.g., non-defenders) to ensure they don't have access to the generated PDF.
  2. Test the behavior when special permissions are granted, as mentioned in the PR objectives.
  3. Verify that the rule correctly handles both allowed and disallowed access scenarios.

Example structure for additional tests:

describe('LimitedAccessCaseController - Get indictment pdf rules', () => {
  // ... existing setup ...

  it('should give permission to defenders', () => {
    // ... existing test ...
  })

  it('should not give permission to non-defenders', () => {
    // Add test logic here
  })

  it('should handle special permissions correctly', () => {
    // Add test logic here
  })

  // Add more test cases as needed
})

These additions would provide more comprehensive coverage of the access control logic implemented in this PR.

apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts (1)

Line range hint 1-18: Changes align with PR objectives for refined access control

The updates to this test file, specifically the use of defenderGeneratedPdfRule, align well with the PR objective of implementing restrictions on access to case files and generated PDFs. This more granular approach to permission handling for generated PDFs suggests improved access control implementation.

However, to ensure comprehensive coverage:

  1. Confirm that similar updates have been made to other relevant test files and components.
  2. Verify that the defenderGeneratedPdfRule correctly implements the intended access restrictions for civil claimant spokespersons.
  3. Ensure that documentation has been updated to reflect these changes in access control logic.

Consider adding a test case that specifically verifies the behavior for civil claimant spokespersons, as mentioned in the PR objectives. This would help ensure that the new access control logic meets the requirements for this user role.

apps/judicial-system/backend/src/app/modules/case/interceptors/limitedAccessCaseFile.interceptor.ts (1)

Line range hint 1-38: Approval of overall implementation with a minor suggestion

The implementation of the LimitedAccessCaseFileInterceptor is well-structured and follows NestJS best practices. It effectively uses TypeScript for type safety and RxJS for data transformation, which aligns with the coding guidelines for NextJS applications.

The interceptor's logic correctly implements the PR objective of restricting access to case files based on user permissions, now including considerations for defendants and civil claimants.

To improve code readability, consider destructuring the theCase object in the filter function to make the code more concise:

const caseFiles = theCase.caseFiles?.filter(
  ({ category }) =>
    canLimitedAcccessUserViewCaseFile(
      user,
      theCase.type,
      theCase.state,
      category,
      theCase.defendants,
      theCase.civilClaimants,
    ),
)

This change would make the code slightly more readable while maintaining the same functionality.

apps/judicial-system/backend/src/app/modules/case/index.ts (1)

12-12: LGTM! Consider grouping related exports.

The addition of defenderGeneratedPdfRule aligns well with the PR objectives for enhancing access control for civil claimants' spokespersons. The export statement is correctly implemented and maintains the existing file structure.

For improved readability and organization, consider grouping related exports together. For instance, you could group all guard-related exports, including this new rule, in one section of the file.

apps/judicial-system/backend/src/app/modules/case/filters/test/publicProsecutionUserFilter.spec.ts (1)

34-49: Well-structured test suite for accessible case types.

The organization of tests for accessible case types is logical and comprehensive. The use of describe.each(indictmentCases) and the filtering of case states ensure thorough testing of access control.

To improve clarity, consider adding a brief comment explaining the purpose of the accessibleCaseStates variable.

Consider adding a comment like this:

// Define states where access should be granted
const accessibleCaseStates = completedCaseStates
apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (2)

44-45: LGTM! Consider destructuring for improved readability.

The addition of theCase.defendants and theCase.civilClaimants as parameters to canLimitedAcccessUserViewCaseFile aligns well with the PR objectives of enhancing access for civil claimants' spokespersons. The implementation maintains the integrity of the guard while extending its functionality.

For improved readability, consider destructuring theCase at the beginning of the method:

const { type, state, defendants, civilClaimants } = theCase;

if (
  canLimitedAcccessUserViewCaseFile(
    user,
    type,
    state,
    caseFile.category,
    defendants,
    civilClaimants
  )
) {
  return true;
}

This change would make the function call cleaner and more concise.


Line range hint 23-35: Enhance error messages for improved debugging

While the current error handling is appropriate, consider enhancing the error messages to provide more context about where the error occurred. This can significantly aid in debugging and troubleshooting.

Here's an example of how you could improve the error messages:

if (!user) {
  throw new InternalServerErrorException('Missing user in LimitedAccessViewCaseFileGuard');
}

if (!theCase) {
  throw new InternalServerErrorException('Missing case in LimitedAccessViewCaseFileGuard');
}

if (!caseFile) {
  throw new InternalServerErrorException('Missing case file in LimitedAccessViewCaseFileGuard');
}

These more detailed error messages will make it easier to trace the source of potential issues during runtime.

apps/judicial-system/backend/src/app/modules/defendant/models/civilClaimant.model.ts (2)

23-35: LGTM: Well-implemented static method for spokesperson verification.

The isSpokespersonOfCivilClaimant method is correctly implemented and aligns with the PR objectives. It efficiently checks if a spokesperson is associated with any civil claimant using TypeScript best practices.

Consider a minor optimization:

- normalizeAndFormatNationalId(spokespersonNationalId).includes(
-   civilClaimant.spokespersonNationalId,
+ normalizeAndFormatNationalId(spokespersonNationalId) ===
+   normalizeAndFormatNationalId(civilClaimant.spokespersonNationalId),

This change ensures exact matching and handles potential formatting differences in the stored spokespersonNationalId.


37-50: LGTM: Well-implemented static method for spokesperson case file access verification.

The isSpokespersonOfCivilClaimantWithCaseFileAccess method is correctly implemented, consistent with the previous method, and aligns with the PR objectives. It efficiently checks if a spokesperson has case file access using TypeScript best practices.

Consider the same optimization as suggested for the previous method:

- normalizeAndFormatNationalId(spokespersonNationalId).includes(
-   civilClaimant.spokespersonNationalId,
+ normalizeAndFormatNationalId(spokespersonNationalId) ===
+   normalizeAndFormatNationalId(civilClaimant.spokespersonNationalId),

This change ensures exact matching and handles potential formatting differences in the stored spokespersonNationalId.

apps/judicial-system/backend/src/app/modules/defendant/models/defendant.model.ts (1)

32-43: LGTM: Well-implemented static method with a minor optimization suggestion.

The isDefenderOfDefendant static method is well-implemented and follows TypeScript best practices. It efficiently checks if a given defender national ID matches any of the provided defendants' defender national IDs.

A minor optimization suggestion:

Consider short-circuiting the method when defendants is undefined or empty:

static isDefenderOfDefendant(
  defenderNationalId: string,
  defendants?: Defendant[],
) {
  if (!defendants?.length) return false;
  return defendants.some(
    (defendant) =>
      defendant.defenderNationalId &&
      normalizeAndFormatNationalId(defenderNationalId).includes(
        defendant.defenderNationalId,
      ),
  );
}

This change would improve performance for cases where defendants is undefined or an empty array.

apps/judicial-system/web/src/components/IndictmentCaseFilesList/IndictmentCaseFilesList.tsx (3)

35-35: LGTM! Consider adding JSDoc for the new prop.

The addition of the displayGeneratedPDFs prop enhances the component's flexibility, aligning with the PR objectives. To improve maintainability, consider adding a JSDoc comment explaining the purpose and default value of this prop.

Example JSDoc:

/**
 * Whether to display generated PDFs. Defaults to true.
 */
displayGeneratedPDFs?: boolean;

79-83: LGTM! Consider extracting the subpoena check for improved readability.

The updated showSubpoenaPdf logic correctly implements the new displayGeneratedPDFs prop. To further improve readability, consider extracting the subpoena check into a separate variable:

const hasSubpoenas = workingCase.defendants?.some(
  (defendant) => defendant.subpoenas && defendant.subpoenas.length > 0
);

const showSubpoenaPdf = displayGeneratedPDFs && hasSubpoenas;

This refactoring would make the logic more explicit and easier to understand at a glance.


182-202: LGTM! Consider extracting the police case numbers rendering into a separate component.

The addition of conditional rendering for police case numbers, controlled by displayGeneratedPDFs, is well-implemented and aligns with the PR objectives. To improve code organization and consistency with other sections, consider extracting this block into a separate component:

const PoliceCaseNumbers: FC<{ workingCase: Case; connectedCaseParentId?: string }> = ({ workingCase, connectedCaseParentId }) => (
  <Box marginBottom={5}>
    <Text variant="h4" as="h4" marginBottom={1}>
      {formatMessage(strings.caseFileTitle)}
    </Text>
    {workingCase.policeCaseNumbers?.map((policeCaseNumber, index) => (
      <Box marginBottom={2} key={`${policeCaseNumber}-${index}`}>
        <PdfButton
          caseId={workingCase.id}
          connectedCaseParentId={connectedCaseParentId}
          title={formatMessage(strings.caseFileButtonText, {
            policeCaseNumber,
          })}
          pdfType="caseFilesRecord"
          elementId={policeCaseNumber}
          renderAs="row"
        />
      </Box>
    ))}
  </Box>
);

// Usage in the main component
{displayGeneratedPDFs && <PoliceCaseNumbers workingCase={workingCase} connectedCaseParentId={connectedCaseParentId} />}

This refactoring would improve code organization and make the component more consistent with other sections.

apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (1)

301-301: Approve the normalization of national ID with a suggestion for error handling.

The use of normalizeAndFormatNationalId function improves data consistency and reduces the risk of mismatches due to different formats of national IDs. This change aligns well with best practices for data normalization.

Consider adding error handling for cases where the normalizeAndFormatNationalId function might throw an error:

where: { 
  defenderNationalId: normalizeAndFormatNationalId(nationalId) 
},

Could be improved to:

where: { 
  defenderNationalId: this.safeNormalizeNationalId(nationalId) 
},

And add a new private method:

private safeNormalizeNationalId(nationalId: string): string {
  try {
    return normalizeAndFormatNationalId(nationalId);
  } catch (error) {
    this.logger.warn(`Failed to normalize national ID: ${nationalId}`, { error });
    return nationalId;
  }
}

This approach ensures that the query will still work even if the normalization fails, while also logging the issue for further investigation.

apps/judicial-system/backend/src/app/modules/case/guards/rolesRules.ts (1)

278-307: LGTM: New defenderGeneratedPdfRule implemented correctly.

The new rule for defenders to access generated PDFs is well-implemented and aligns with the PR objectives. It correctly checks for both defenders of defendants and spokespersons of civil claimants with case file access.

Some positive points:

  1. The use of early returns improves readability.
  2. The logic for checking user roles is delegated to the Defendant and CivilClaimant classes, promoting separation of concerns.

Minor suggestion for improvement:

Consider adding a logging statement when user or case is missing, instead of just a comment. This will help with debugging in production. For example:

if (!user || !theCase) {
  console.error('Missing user or case in defenderGeneratedPdfRule');
  return false;
}
apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (2)

56-60: LGTM! Consider grouping related imports.

The addition of defenderGeneratedPdfRule and defenderTransitionRule imports aligns well with the PR objectives for enhancing access control.

Consider grouping all role-related imports together for better organization:

import {
  defenderGeneratedPdfRule,
  defenderTransitionRule,
  defenderUpdateRule,
  defenderRule,
  prisonSystemStaffRule
} from './guards/rolesRules'

383-388: LGTM! Consider updating documentation.

The update to use defenderGeneratedPdfRule for the getIndictmentPdf method is consistent with the changes made to getCaseFilesRecordPdf. This change reinforces granular access control for PDF generation, aligning with the PR objectives.

Consider updating the method's documentation to reflect the new access control:

/**
 * Gets the indictment for an existing case as a pdf document.
 * Access is restricted based on the defenderGeneratedPdfRule.
 */
@ApiOkResponse({
  content: { 'application/pdf': {} },
  description: 'Gets the indictment for an existing case as a pdf document (restricted access)',
})
apps/judicial-system/backend/src/app/modules/case/filters/test/cases.filter.spec.ts (1)

456-475: LGTM! Consider extracting subqueries for improved readability.

The changes successfully implement the new functionality allowing civil claimants' spokespersons to access cases as defenders. The implementation is correct and consistent with the existing code style.

To improve readability, consider extracting the subqueries into separate variables. For example:

const defendantSubquery = Sequelize.literal(`
  (SELECT case_id
   FROM defendant
   WHERE defender_national_id in ('${user.nationalId}', '${user.nationalId}'))
`)

const civilClaimantSubquery = Sequelize.literal(`
  (SELECT case_id
   FROM civil_claimant
   WHERE has_spokesperson = true AND spokesperson_national_id in ('${user.nationalId}', '${user.nationalId}'))
`)

// Then use these variables in the query
{
  [Op.or]: [
    { id: { [Op.in]: defendantSubquery } },
    { id: { [Op.in]: civilClaimantSubquery } },
  ],
}

This approach would make the code more readable and easier to maintain.

apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx (1)

174-174: Address the TODO comment and refine the condition

There's a TODO comment indicating that the condition for displaying case files may not be accurate. It's important to find a more precise condition to ensure generated PDFs are displayed appropriately, even if there are no uploaded files.

Would you like assistance in refining this condition to improve the accuracy of the file display logic?

apps/judicial-system/backend/src/app/modules/case/filters/test/defenceUserFilter.spec.ts (1)

19-20: Update or remove outdated TODO comments

The TODO comments suggest fixing defender indictment tests and adding spokesperson tests. Since the code now includes updated defender indictment tests and new spokesperson tests, consider updating or removing these comments to reflect the current state of the code.

apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts (1)

280-299: Consider adding comments to explain complex query logic

The new query condition involves complex subqueries and multiple logical operators. Adding inline comments to explain the purpose and functionality of this query can improve readability and assist future maintainers in understanding the intent.

apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts (2)

Line range hint 431-467: Enhance error handling and code readability in findDefenderByNationalId

  • The exception message 'Defender not found' may not fully reflect the possible cases being handled, as it now includes civil claimant spokespersons. Consider updating the message to be more descriptive, such as 'No associated defender or spokesperson found for the provided national ID'.

  • The nested .then() calls could be refactored using async/await for better readability and maintainability.

Suggested changes:

Update the exception message at line 466:

-                    throw new NotFoundException('Defender not found')
+                    throw new NotFoundException('No associated defender or spokesperson found for the provided national ID')

Refactor the method to use async/await:

async findDefenderByNationalId(nationalId: string): Promise<User> {
  const theCase = await this.caseModel.findOne({
    where: {
      defenderNationalId: normalizeAndFormatNationalId(nationalId),
      state: { [Op.not]: CaseState.DELETED },
      isArchived: false,
    },
    order: [['created', 'DESC']],
  });

  if (theCase) {
    // The national ID is associated with a defender in a request case
    return this.constructDefender(
      nationalId,
      theCase.defenderName,
      theCase.defenderPhoneNumber,
      theCase.defenderEmail,
    );
  }

  const defendant = await this.defendantService.findLatestDefendantByDefenderNationalId(nationalId);

  if (defendant) {
    // The national ID is associated with a defender in an indictment case
    return this.constructDefender(
      nationalId,
      defendant.defenderName,
      defendant.defenderPhoneNumber,
      defendant.defenderEmail,
    );
  }

  const civilClaimant = await this.civilClaimantService.findLatestClaimantBySpokespersonNationalId(nationalId);

  if (civilClaimant) {
    // The national ID is associated with a spokesperson for a civil claimant in an indictment case
    return this.constructDefender(
      nationalId,
      civilClaimant.spokespersonName,
      civilClaimant.spokespersonPhoneNumber,
      civilClaimant.spokespersonEmail,
    );
  }

  throw new NotFoundException('No associated defender or spokesperson found for the provided national ID');
}

431-431: Consistent capitalization of 'ID' in comments

Please capitalize 'ID' in comments to maintain consistency and adhere to standard conventions.

Also applies to: 444-444, 457-457

apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (3)

175-185: Ensure consistency in test descriptions and structure

The test descriptions vary in wording and structure. Standardizing the test descriptions improves clarity. For example, use a consistent pattern like 'when the user is a defender with case files access, they can view %s'.

Here's how you might revise the test descriptions:

-describe('a defender with case files access can view', () => {
+describe(`when the user is a defender with case files access, they can view ${category}`, () => {

This change provides a clearer context for each test scenario.

Also applies to: 198-214, 235-242, 261-276, 306-315, 328-343, 364-372, 389-404


175-185: Simplify the usage of uuid() for national IDs in tests

Using uuid() generates a UUID, which doesn't match the format of an Icelandic national ID (kennitala). While it may not affect the test outcome, using a realistic format improves test reliability.

Consider updating the nationalId to a realistic mock value:

-                    const nationalId = uuid()
+                    const nationalId = '010130-1234' // Example kennitala

175-185: Add type annotations for better type safety

Some variables, such as nationalId and then, lack explicit type annotations. Adding these annotations enhances code clarity and leverages TypeScript's type-checking capabilities.

For example:

let then: Then
let nationalId: string

beforeEach(() => {
  nationalId = uuid()
  // rest of the code
})

This practice ensures that the variables have the expected types throughout the test cases.

Also applies to: 198-214, 235-242, 261-276, 306-315, 328-343, 364-372, 389-404

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 330e4c1 and 972e8d2.

📒 Files selected for processing (32)
  • apps/judicial-system/api/src/app/modules/auth/auth.controller.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/filters/case.filter.ts (6 hunks)
  • apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/filters/test/cases.filter.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/filters/test/defenceUserFilter.spec.ts (4 hunks)
  • apps/judicial-system/backend/src/app/modules/case/filters/test/publicProsecutionUserFilter.spec.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/guards/rolesRules.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/index.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/interceptors/limitedAccessCaseFile.interceptor.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (3 hunks)
  • apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts (6 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/createTestingCaseModule.ts (5 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/findDefenderByNationalId.spec.ts (3 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfGuards.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getIndictmentPdfGuards.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getIndictmentPdfRolesRules.spec.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/civilClaimant.service.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/defendant.module.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/defendant.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/index.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/models/civilClaimant.model.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/defendant/models/defendant.model.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (3 hunks)
  • apps/judicial-system/backend/src/app/modules/file/index.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/limitedAccessSubpoena.controller.ts (3 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/test/limitedAccessSubpoenaController/getSubpoenaPdfRolesRules.spec.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/test/limitedAccessSubpoenaController/limitedAccessSubpoenaControllerGuards.spec.ts (1 hunks)
  • apps/judicial-system/web/src/components/IndictmentCaseFilesList/IndictmentCaseFilesList.tsx (5 hunks)
  • apps/judicial-system/web/src/routes/Shared/IndictmentOverview/IndictmentOverview.tsx (3 hunks)
🧰 Additional context used
📓 Path-based instructions (32)
apps/judicial-system/api/src/app/modules/auth/auth.controller.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/filters/case.filter.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/filters/cases.filter.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/filters/test/cases.filter.spec.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/filters/test/defenceUserFilter.spec.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/filters/test/publicProsecutionUserFilter.spec.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/guards/rolesRules.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/index.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/interceptors/limitedAccessCaseFile.interceptor.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/limitedAccessCase.controller.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/limitedAccessCase.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/modules/case/test/createTestingCaseModule.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/test/limitedAccessCaseController/findDefenderByNationalId.spec.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/test/limitedAccessCaseController/getCaseFilesRecordPdfGuards.spec.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/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.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/test/limitedAccessCaseController/getIndictmentPdfGuards.spec.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/test/limitedAccessCaseController/getIndictmentPdfRolesRules.spec.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/defendant/civilClaimant.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/modules/defendant/defendant.module.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/defendant/defendant.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/modules/defendant/index.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/defendant/models/civilClaimant.model.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/defendant/models/defendant.model.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/file/guards/caseFileCategory.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/file/guards/limitedAccessViewCaseFile.guard.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/file/guards/test/limitedAccessViewCaseFileGuard.spec.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/file/index.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/subpoena/limitedAccessSubpoena.controller.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/subpoena/test/limitedAccessSubpoenaController/getSubpoenaPdfRolesRules.spec.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/subpoena/test/limitedAccessSubpoenaController/limitedAccessSubpoenaControllerGuards.spec.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/IndictmentCaseFilesList/IndictmentCaseFilesList.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/Shared/IndictmentOverview/IndictmentOverview.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."
📓 Learnings (3)
apps/judicial-system/backend/src/app/modules/defendant/defendant.module.ts (2)
Learnt from: oddsson
PR: island-is/island.is#16059
File: apps/judicial-system/backend/src/app/modules/defendant/defendant.module.ts:28-28
Timestamp: 2024-09-18T14:32:59.502Z
Learning: Services should only be exported when they are needed by other modules.
Learnt from: oddsson
PR: island-is/island.is#16059
File: apps/judicial-system/backend/src/app/modules/defendant/defendant.module.ts:28-28
Timestamp: 2024-10-08T15:39:04.351Z
Learning: Services should only be exported when they are needed by other modules.
apps/judicial-system/backend/src/app/modules/defendant/index.ts (4)
Learnt from: oddsson
PR: island-is/island.is#16059
File: apps/judicial-system/backend/src/app/modules/defendant/defendant.module.ts:28-28
Timestamp: 2024-09-18T14:32:59.502Z
Learning: Services should only be exported when they are needed by other modules.
Learnt from: oddsson
PR: island-is/island.is#16059
File: apps/judicial-system/backend/src/app/modules/defendant/defendant.module.ts:28-28
Timestamp: 2024-10-08T15:39:04.351Z
Learning: Services should only be exported when they are needed by other modules.
Learnt from: oddsson
PR: island-is/island.is#16059
File: apps/judicial-system/backend/src/app/modules/defendant/civilClaimant.service.ts:35-43
Timestamp: 2024-10-08T15:39:04.351Z
Learning: In this codebase, when an update operation affects multiple rows instead of one, it is acceptable to log the error without throwing an exception.
Learnt from: oddsson
PR: island-is/island.is#16059
File: apps/judicial-system/backend/src/app/modules/defendant/civilClaimant.service.ts:35-43
Timestamp: 2024-09-18T14:52:42.008Z
Learning: In this codebase, when an update operation affects multiple rows instead of one, it is acceptable to log the error without throwing an exception.
apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (2)
Learnt from: oddsson
PR: island-is/island.is#16138
File: apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts:74-87
Timestamp: 2024-10-08T15:39:04.351Z
Learning: User prefers to keep similar conditional statements separate rather than combining them into a single conditional with logical operators.
Learnt from: oddsson
PR: island-is/island.is#16138
File: apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts:74-87
Timestamp: 2024-09-24T20:55:56.753Z
Learning: User prefers to keep similar conditional statements separate rather than combining them into a single conditional with logical operators.
🔇 Additional comments (56)
apps/judicial-system/backend/src/app/modules/file/index.ts (1)

5-5: LGTM! Verify usage of the renamed export.

The change from defenderCaseFileCategoriesForRestrictionAndInvestigationCases to defenderCaseFileCategoriesForRequestCases looks good and aligns with the PR objectives. This modification suggests a shift in focus to request cases, which may be relevant to the enhanced access for civil claimants' spokespersons.

To ensure this change doesn't break existing functionality, please run the following script to check for any remaining usage of the old export name:

Make sure to update any imports of this variable throughout the application if necessary.

✅ Verification successful

Verification Successful: Renaming confirmed and no old export name usage found.

The renaming of defenderCaseFileCategoriesForRestrictionAndInvestigationCases to defenderCaseFileCategoriesForRequestCases has been successfully verified. No remaining references to the old export name were found, and all usages now refer to the new export name.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of the old export name

# Test: Search for the old export name. Expect: No results.
rg --type typescript "defenderCaseFileCategoriesForRestrictionAndInvestigationCases" apps/judicial-system

# Test: Search for the new export name. Expect: At least one result (the current file).
rg --type typescript "defenderCaseFileCategoriesForRequestCases" apps/judicial-system

Length of output: 261


Script:

#!/bin/bash
# Description: Check for any remaining usage of the old export name using the correct file type

# Test: Search for the old export name. Expect: No results.
rg --type ts "defenderCaseFileCategoriesForRestrictionAndInvestigationCases" apps/judicial-system

# Test: Search for the new export name. Expect: At least one result (the current file).
rg --type ts "defenderCaseFileCategoriesForRequestCases" apps/judicial-system

Length of output: 878

apps/judicial-system/backend/src/app/modules/defendant/index.ts (1)

6-6: Verify the necessity of exporting CivilClaimantService.

The addition of the CivilClaimantService export aligns with the PR objectives for enhancing civil claimant spokesperson access. However, based on previous learnings, services should only be exported when needed by other modules.

Please confirm that this service is required by other modules outside of the defendant module. If it's not strictly necessary, consider keeping it internal to the module to maintain encapsulation.

To verify the usage, you can run the following script:

If there are no results, consider refactoring to keep the service internal:

-export { CivilClaimantService } from './civilClaimant.service'

This approach would better align with the learned best practices for service exports in this codebase.

apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getIndictmentPdfRolesRules.spec.ts (1)

1-1: LGTM! Verify the new import path.

The change from defenderRule to defenderGeneratedPdfRule aligns with the PR objectives of implementing restrictions on access to generated PDFs. This more specific rule name improves code clarity.

Please run the following script to verify the new import path:

apps/judicial-system/backend/src/app/modules/subpoena/test/limitedAccessSubpoenaController/getSubpoenaPdfRolesRules.spec.ts (3)

1-1: Import statement updated to reflect new access control logic.

The import has been changed from defenderRule to defenderGeneratedPdfRule, and the import path has been updated accordingly. This change aligns with the PR objectives of refining access control for civil claimant spokespersons.


17-17: Test expectation updated to match new rule.

The test expectation has been correctly updated to check for defenderGeneratedPdfRule instead of defenderRule. This change is consistent with the import modification and ensures that the test accurately reflects the new access control logic.


Line range hint 1-17: Changes align with PR objectives and coding guidelines.

The modifications in this test file contribute to the PR objective of implementing restrictions on access to generated PDFs. The updated rule (defenderGeneratedPdfRule) reflects the refined access control logic for defenders, which is crucial for the new functionality allowing civil claimants' spokespersons to log in as defenders.

While this is a test file and doesn't directly involve NextJS or state management, it ensures the correct implementation of the access control logic, which is essential for the overall application structure. The use of TypeScript is appropriate, maintaining type safety in the test setup.

These changes indirectly support the coding guidelines by ensuring that the core functionality is properly tested, which is a best practice in NextJS and TypeScript development.

apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts (1)

17-17: Updated test expectation to match new rule

The test expectation has been updated to check for defenderGeneratedPdfRule instead of defenderRule. This change aligns with the updated import and reflects the more specific permission check for generated PDFs.

To ensure this change is comprehensive, let's verify if there are any other test files that might need similar updates:

#!/bin/bash
# Description: Check for other test files that might need similar updates

echo "Searching for other test files that might reference 'defenderRule':"
rg "defenderRule" --type ts -g "*spec.ts" -g "*test.ts"

echo "\nSearching for other test files that use 'getCaseFilesRecordPdf':"
rg "getCaseFilesRecordPdf" --type ts -g "*spec.ts" -g "*test.ts"
apps/judicial-system/backend/src/app/modules/case/interceptors/limitedAccessCaseFile.interceptor.ts (1)

29-30: Enhancement of access control logic for case files

The addition of theCase.defendants and theCase.civilClaimants as parameters to the canLimitedAcccessUserViewCaseFile function aligns with the PR objective of enabling civil claimants' spokespersons to access relevant case information. This change allows for more granular access control based on the specific defendants and civil claimants associated with a case.

However, there are a few points to consider:

  1. Ensure that the canLimitedAcccessUserViewCaseFile function in the file module has been updated to handle these new parameters correctly.
  2. Verify that this change doesn't unintentionally grant access to users who shouldn't have it.
  3. Consider adding a comment explaining the purpose of these new parameters for better code maintainability.

To ensure the canLimitedAcccessUserViewCaseFile function has been updated correctly, please run the following script:

This script will help us confirm that the function signature has been updated to match the new usage in this interceptor.

apps/judicial-system/backend/src/app/modules/defendant/defendant.module.ts (1)

29-29: Verify the necessity of exporting CivilClaimantService

The addition of CivilClaimantService to the exports array aligns with the PR objectives for enhancing access for civil claimants' spokespersons. However, based on previous learnings, services should only be exported when needed by other modules.

  1. Please verify if exporting CivilClaimantService is necessary. Are there other modules that require direct access to this service?
  2. If the export is necessary, consider adding a comment explaining why it needs to be exported, to maintain clear documentation.
  3. If it's not necessary, consider removing it from the exports array to keep the module's public API minimal.

To ensure this export is used, you can run the following command to search for imports of CivilClaimantService from DefendantModule:

This will help verify if the export is actually being used in other parts of the application.

apps/judicial-system/backend/src/app/modules/case/filters/test/publicProsecutionUserFilter.spec.ts (2)

Line range hint 17-33: Excellent restructuring of the test suite!

The new structure using describe.each(publicProsecutorRoles) is a great improvement. It efficiently tests all public prosecutor roles without code duplication. The organization of test cases by inaccessible and accessible case types enhances readability and maintainability.

This change aligns well with the PR objectives by thoroughly testing access control for different user roles.


Line range hint 1-49: Compliance with coding guidelines confirmed.

The file adheres to the relevant coding guidelines for the apps directory:

  • Optimal use of TypeScript for type safety is evident throughout the file.
  • The file structure and naming convention follow best practices for testing.

While NextJS-specific guidelines are not directly applicable to this test file, the overall structure and approach align well with general best practices for testing in a TypeScript environment.

apps/judicial-system/backend/src/app/modules/subpoena/test/limitedAccessSubpoenaController/limitedAccessSubpoenaControllerGuards.spec.ts (2)

Line range hint 1-30: LGTM: Well-structured test file with proper TypeScript usage.

The overall structure of the test file is clear, well-organized, and follows good TypeScript practices. The test adequately covers the guard configuration for the LimitedAccessSubpoenaController.


20-21: Verify the intentionality and impact of guard order change.

The order of guard instance checks for CaseExistsGuard and RolesGuard has been swapped. While this change doesn't affect the test's validity, it's important to ensure that this modification aligns with the intended guard execution order in the actual implementation.

To confirm the correct order of guards in the controller, please run the following script:

If the order in the controller matches this test, the change is correct. Otherwise, please adjust either the test or the controller to ensure consistency.

apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfGuards.spec.ts (1)

24-25: Verify guard order in the actual implementation

The change in the order of guard expectations looks good. However, it's crucial to ensure that this change aligns with the actual implementation of the getCaseFilesRecordPdf method in the LimitedAccessCaseController.

Let's verify the actual guard order in the LimitedAccessCaseController:

Please review the output of this script to confirm that the guard order in the actual implementation matches the updated test expectations.

apps/judicial-system/backend/src/app/modules/subpoena/limitedAccessSubpoena.controller.ts (4)

30-30: LGTM: Import change aligns with PR objectives

The import of defenderGeneratedPdfRule instead of the previous defenderRule aligns well with the PR objective of implementing restrictions on access to generated PDFs. This change suggests a more granular approach to access control, which is a good practice in NextJS applications.


57-57: LGTM: Decorator change enhances access control

The update to @RolesRules(defenderGeneratedPdfRule) is a positive change that aligns with the PR objective of implementing restrictions on access to generated PDFs. This more specific rule enhances the granularity of access control for the getSubpoenaPdf method. The implementation adheres to TypeScript and NextJS best practices, maintaining type safety and the overall structure of the controller.


44-44: Please clarify the guard order change

The RolesGuard has been moved after CaseExistsGuard in the @UseGuards decorator. While this change aligns with the overall goal of refining access control, could you please clarify:

  1. The rationale behind this specific order change?
  2. Any potential impacts on the access validation flow?
  3. How this change ensures that no security vulnerabilities are introduced?

This information will help ensure that the change maintains the intended security model while meeting the PR objectives.


Line range hint 1-85: Implementation aligns with PR objectives, but additional context needed

The changes in this file effectively address the PR objective of implementing restrictions on access to generated PDFs. The use of defenderGeneratedPdfRule and the refinement of the @RolesRules decorator demonstrate a more granular approach to access control.

However, to fully understand how this PR meets all stated objectives, could you please provide additional context on:

  1. How these changes enable civil claimants' spokespersons to log in as defenders?
  2. Where and how the cases assigned to these spokespersons are displayed?
  3. How the option to add documents after case conclusion is removed for spokespersons?

This additional information will help ensure that all PR objectives are met across the codebase.

apps/judicial-system/backend/src/app/modules/defendant/models/civilClaimant.model.ts (2)

9-9: LGTM: Import statements are correctly updated.

The new imports for UpdatedAt decorator and normalizeAndFormatNationalId function are appropriate for the added functionality. They follow TypeScript best practices and are used effectively in the new code.

Also applies to: 14-15


61-68: LGTM with a question: Property changes for tracking creation and modification times.

The addition of the modified property with the @UpdatedAt decorator is a good practice for tracking updates. Setting timestamps: false in the @Table decorator is consistent with manually defining these fields.

However, I have a question about the created property:

The column definition for the created property has been removed. Can you confirm that this won't affect how the creation timestamp is handled? If it does change the behavior, please explain the intended functionality.

To verify the current behavior, you can run the following script:

This script will help us understand how the 'created' and 'modified' fields are currently defined and populated in the database.

✅ Verification successful

Verified: Creation and modification timestamp handling is correctly implemented.

The created property in the backend model retains the @CreatedAt decorator, ensuring that the creation timestamp is automatically managed despite the removal of its explicit column definition. The addition of the modified property with the @UpdatedAt decorator correctly handles update timestamps. Both changes align with best practices for timestamp management.

  • Backend Model (apps/judicial-system/backend/src/app/modules/defendant/models/civilClaimant.model.ts):

    • @CreatedAt @ApiProperty({ type: Date }) created!: Date
    • @UpdatedAt @ApiProperty({ type: Date }) modified!: Date
  • API Model (apps/judicial-system/api/src/app/modules/defendant/models/civilClaimant.model.ts):

    • @Field(() => String, { nullable: true }) readonly created?: string
    • @Field(() => String, { nullable: true }) readonly modified?: string
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the behavior of the 'created' field in the database

# Test: Inspect the database schema for the 'civil_claimant' table
echo "Inspecting database schema for 'civil_claimant' table:"
npx sequelize-cli db:describe --table civil_claimant

# Test: Check a sample record to see how 'created' and 'modified' fields are populated
echo "Checking sample record for 'created' and 'modified' fields:"
npx sequelize-cli db:select --table civil_claimant --attributes id,created,modified --limit 1

Length of output: 559


Script:

#!/bin/bash
# Description: Extract 'created' and 'modified' property definitions in CivilClaimant model

# Search for the CivilClaimant model class
ast-grep --lang typescript --pattern 'class CivilClaimant { $$$ }' src/app/modules/defendant/models/civilClaimant.model.ts

# Extract the 'created' property with its decorators
ast-grep --lang typescript --pattern '@CreatedAt @ApiProperty({ type: Date }) created!: Date' src/app/modules/defendant/models/civilClaimant.model.ts

# Extract the 'modified' property with its decorators
ast-grep --lang typescript --pattern '@UpdatedAt @ApiProperty({ type: Date }) modified!: Date' src/app/modules/defendant/models/civilClaimant.model.ts

Length of output: 1487


Script:

#!/bin/bash
# Description: Locate the 'civilClaimant.model.ts' file in the codebase

fd 'civilClaimant\.model\.ts$' src/

Length of output: 129


Script:

#!/bin/bash
# Description: Locate the 'civilClaimant.model.ts' file in the entire codebase

fd 'civilClaimant\.model\.ts$'

Length of output: 198


Script:

#!/bin/bash
# Description: Extract 'created' and 'modified' property definitions from CivilClaimant model files

# Define file paths
BACKEND_FILE="apps/judicial-system/backend/src/app/modules/defendant/models/civilClaimant.model.ts"
API_FILE="apps/judicial-system/api/src/app/modules/defendant/models/civilClaimant.model.ts"

# Extract 'created' property definitions
echo "Extracting 'created' property from backend model:"
rg -C 2 'created' "$BACKEND_FILE"

echo "Extracting 'created' property from API model:"
rg -C 2 'created' "$API_FILE"

# Extract 'modified' property definitions
echo "Extracting 'modified' property from backend model:"
rg -C 2 'modified' "$BACKEND_FILE"

echo "Extracting 'modified' property from API model:"
rg -C 2 'modified' "$API_FILE"

Length of output: 1438

apps/judicial-system/backend/src/app/modules/defendant/models/defendant.model.ts (2)

15-15: LGTM: Import statement is correct and necessary.

The import of normalizeAndFormatNationalId from '@island.is/judicial-system/formatters' is appropriate and follows TypeScript best practices. This function is used in the newly added static method, justifying its inclusion.


Line range hint 1-43: Summary: Changes align well with PR objectives and follow best practices.

The additions to the Defendant model, including the new isDefenderOfDefendant static method, align well with the PR objectives of enhancing access for civil claimants' spokespersons. This method provides a crucial functionality for verifying defender access, which is essential for implementing the access control logic described in the PR objectives.

The changes follow TypeScript and NextJS best practices, including proper type annotations and efficient implementation. The use of the normalizeAndFormatNationalId function ensures consistent handling of national IDs, which is important for reliable access control.

Overall, these changes contribute positively to the goal of enabling civil claimants' spokespersons to log in as defenders while maintaining proper access restrictions.

apps/judicial-system/backend/src/app/modules/case/test/createTestingCaseModule.ts (6)

21-21: LGTM: Import statement for CivilClaimantService

The import statement for CivilClaimantService is correctly placed and follows the existing import structure. The relative path seems appropriate for the project structure.


49-49: LGTM: Mock statement for CivilClaimantService

The jest.mock statement for CivilClaimantService is correctly placed with other similar mock statements. Mocking the service is a good practice for isolating the test environment and ensuring consistent behavior during testing.


75-75: LGTM: CivilClaimantService added to providers

The CivilClaimantService is correctly added to the providers array. This ensures that the service is properly instantiated and available for dependency injection within the testing module, following NestJS best practices.


154-156: LGTM: civilClaimantService added to return object

The civilClaimantService is correctly retrieved from the module and added to the return object. The multi-line format is consistent with other similar statements in the file. This addition allows the service to be easily accessed in tests that use this module, promoting good test structure and reusability.


206-206: LGTM: civilClaimantService added to final return object

The civilClaimantService is correctly added to the final return object of the createTestingCaseModule function. This ensures that the service is available for use in tests that consume this module, maintaining consistency with other services and following good testing practices.


Line range hint 1-220: Summary: Successful integration of CivilClaimantService into the testing module

The changes in this file effectively integrate the CivilClaimantService into the testing module for the case system. The modifications include:

  1. Importing the service
  2. Mocking it for testing
  3. Adding it to the providers array
  4. Including it in the module's return object

These changes align with the PR objectives of enhancing access for civil claimants' spokespersons by making the service available for testing. The implementation follows NextJS and NestJS best practices, maintaining consistency with the existing code structure.

apps/judicial-system/web/src/components/IndictmentCaseFilesList/IndictmentCaseFilesList.tsx (1)

67-67: LGTM! Default value ensures backward compatibility.

The default value of true for displayGeneratedPDFs is a good choice. It maintains backward compatibility with existing usage of the component while allowing new implementations to control the display of generated PDFs as needed.

apps/judicial-system/api/src/app/modules/auth/auth.controller.ts (1)

259-268: LGTM with suggestions for improvement

The restructuring of the authorizeUser method improves code readability and ensures consistent checking for both users and defenders. This aligns well with the PR objective of enabling civil claimants' spokespersons to log in as defenders. However, consider the following suggestions:

  1. The method now always performs two database queries (for user and defender), which might impact performance. Consider optimizing this if it becomes a bottleneck.

  2. The current implementation doesn't handle the case where a national ID belongs to both a user and a defender. Please clarify how this scenario should be handled.

  3. To fully meet the PR objectives, consider adding explicit handling for civil claimant spokespersons. This could involve checking for a specific role or permission within the defender object.

To verify the impact of these changes, please run the following script:

apps/judicial-system/backend/src/app/modules/case/guards/rolesRules.ts (2)

9-9: LGTM: New imports added for CivilClaimant and Defendant.

The new imports are correctly added and are necessary for the new defenderGeneratedPdfRule. The relative import path follows the project structure.


Line range hint 1-307: Summary: Changes align well with PR objectives.

The modifications to this file successfully implement the new access control for civil claimant spokespersons, as outlined in the PR objectives. The new defenderGeneratedPdfRule allows civil claimants' spokespersons to access generated PDFs when they have the necessary permissions, while maintaining security by checking for the appropriate roles and access rights.

The implementation adheres to NextJS best practices and makes efficient use of TypeScript for type safety. The code structure and logic are clear and maintainable.

apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.controller.ts (2)

Line range hint 1-438: Overall assessment: Changes improve access control as intended.

The modifications to this controller consistently implement more granular access control for PDF generation, aligning well with the PR objectives. The use of defenderGeneratedPdfRule enhances the security model by providing finer-grained control over access to case files and generated PDFs.

Key points:

  1. Import statements have been updated to include new role-based access control rules.
  2. The getCaseFilesRecordPdf and getIndictmentPdf methods now use the new defenderGeneratedPdfRule.
  3. These changes maintain existing security measures while introducing more specific access controls.

To further improve the code:

  1. Consider grouping related imports for better organization.
  2. Update method documentation to reflect the new access control rules.
  3. Verify that the new rules don't unintentionally restrict legitimate access.

Great job on enhancing the security and access control of the judicial system application!


248-253: LGTM! Verify the impact of the new rule.

The update to use defenderGeneratedPdfRule aligns with the PR objectives for refining access control. This change provides more granular control over who can access case file records.

To ensure this change doesn't unintentionally restrict access, please run the following verification:

✅ Verification successful

Verified: defenderGeneratedPdfRule Provides More Granular Access Control

The defenderGeneratedPdfRule introduces additional checks to ensure that only authorized defenders or spokespersons can access case file records, enhancing the security and specificity of access permissions.

  • defenderGeneratedPdfRule is defined in apps/judicial-system/backend/src/app/modules/case/guards/rolesRules.ts
  • defenderRule is defined in apps/judicial-system/backend/src/app/guards/rolesRules.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of defenderGeneratedPdfRule on existing defender access

# Test: Check if defenderGeneratedPdfRule is more restrictive than defenderRule
ast-grep --lang typescript --pattern 'function defenderGeneratedPdfRule($user) { $$ }'

# Test: Ensure defenderGeneratedPdfRule is used consistently
rg "defenderGeneratedPdfRule" --type typescript

Length of output: 171


Script:

#!/bin/bash
# Description: Verify the impact of defenderGeneratedPdfRule on existing defender access

# Test: Check if defenderGeneratedPdfRule is more restrictive than defenderRule
ast-grep --lang typescript --pattern 'function defenderGeneratedPdfRule($user) { $$ }'

# Test: Ensure defenderGeneratedPdfRule is used consistently
rg "defenderGeneratedPdfRule" --type ts

Length of output: 2059


Script:

#!/bin/bash
# Description: Extract the definition of defenderGeneratedPdfRule for analysis

# Extract the defenderGeneratedPdfRule definition from rolesRules.ts
ast-grep --lang typescript --pattern 'export const defenderGeneratedPdfRule: RolesRule = { $$$ }' apps/judicial-system/backend/src/app/modules/case/guards/rolesRules.ts

Length of output: 3041


Script:

#!/bin/bash
# Description: Extract the definition of defenderRule for analysis

# Extract the defenderRule definition from rolesRules.ts
ast-grep --lang typescript --pattern 'export const defenderRule: RolesRule = { $$$ }' apps/judicial-system/backend/src/app/modules/case/guards/rolesRules.ts

Length of output: 158


Script:

#!/bin/bash
# Description: Search for the definition of defenderRule across the codebase

# Search for the export of defenderRule in any TypeScript file
rg 'export\s+const\s+defenderRule' --type ts

Length of output: 161

apps/judicial-system/backend/src/app/modules/defendant/civilClaimant.service.ts (2)

84-86: Double-check the filtering conditions in the include clause

In your query's include clause, you filter Case records where state is not DELETED and isArchived is false. Ensure that these conditions align with the business logic, and consider whether additional states or flags should be included or excluded.


90-91: ⚠️ Potential issue

Ensure proper handling and validation of national IDs

You're using normalizeAndFormatNationalId(nationalId) to normalize the input. Please confirm that this function adequately validates the nationalId and handles any invalid or malformed inputs gracefully to prevent potential errors or security issues.

Run the following script to inspect the implementation of normalizeAndFormatNationalId:

apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (1)

132-153: Verify that all invocations of 'canLimitedAccessUserViewCaseFile' are updated with new parameters

The signature of canLimitedAccessUserViewCaseFile has been updated to include defendants and civilClaimants parameters. Please ensure that all calls to this function have been updated accordingly to prevent potential runtime errors.

Run the following script to verify function invocations:

apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/findDefenderByNationalId.spec.ts (3)

169-200: Well-structured test case for civil claimant spokespersons.

The addition of this test case effectively covers the scenario where a defender is found in a civil claimant, enhancing test coverage and ensuring the functionality works as intended.


186-198: Verify the appropriateness of the title field value for spokespersons.

In the returned user object, the title field is set to 'verjandi' (defender). Since the user represents a civil claimant's spokesperson, please verify if 'verjandi' is the correct title. If a different title such as 'talsmaður' (spokesperson) is more accurate, consider updating it accordingly.

To verify the usage of the title field for different user roles, you can run:

#!/bin/bash
# Description: Verify the `title` values assigned to users in different contexts.

# Test: Search for assignments of the `title` field in user objects.
# Expect: Appropriate titles are assigned based on user roles.

rg --type ts "title: '\\w+'" -A 5

12-12: Verify the import path of CivilClaimantService.

Please ensure that CivilClaimantService is correctly imported from the appropriate module. If CivilClaimantService is defined in a different module or directory, update the import path accordingly.

To verify where CivilClaimantService is defined, you can run:

✅ Verification successful

Verified: The CivilClaimantService is correctly imported from the ../../../defendant module.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the definition location of `CivilClaimantService`.

# Test: Search for the definition of `CivilClaimantService`.
# Expect: The class is exported from the correct module.

rg --type ts 'export class CivilClaimantService' -A 5

Length of output: 190705


Script:

#!/bin/bash
# Description: Verify the definition location of `CivilClaimantService`.

# Test: Search for the definition of `CivilClaimantService`.
# Expect: The class is exported from the correct module.

rg --type ts 'export\s+class\s+CivilClaimantService\b' -A 5

Length of output: 756

apps/judicial-system/backend/src/app/modules/case/filters/test/defenceUserFilter.spec.ts (3)

5-6: Refactored case states improve clarity

Splitting completedCaseStates into completedIndictmentCaseStates and completedRequestCaseStates enhances readability and maintainability by clearly separating indictment and request case states.


17-17: Imported verifyReadAccess for spokesperson tests

Adding verifyReadAccess to the imports enables testing of read-only access for spokesperson roles, aligning with the new test cases added below.


266-279: Ensure correct access verification for spokesperson assigned to case

The test correctly uses verifyReadAccess for a spokesperson assigned to the case. This validates that the spokesperson has read-only access, which aligns with the intended access control for spokesperson roles.

apps/judicial-system/backend/src/app/modules/case/filters/cases.filter.ts (2)

280-299: LGTM

The updated query filter correctly includes cases where the defense user is a spokesperson, aligning with the PR objectives.


280-299: ⚠️ Potential issue

Avoid using Sequelize.literal with string interpolation to prevent SQL injection risks

Using Sequelize.literal with string interpolation of variables that may be influenced by user input can expose the application to SQL injection attacks. It's safer to use parameterized queries or Sequelize's query interface to build queries with proper parameterization. Consider refactoring the subqueries to use Sequelize methods to ensure security and maintainability.

To verify the safety of the normalizedNationalId and formattedNationalId variables, run the following script to check the implementation of normalizeAndFormatNationalId:

apps/judicial-system/backend/src/app/modules/case/filters/case.filter.ts (7)

Line range hint 310-361: Review the implementation of 'canDefenceUserAccessRequestCase'

The new function canDefenceUserAccessRequestCase improves the granularity of access control for defence users on request cases. The logic appears sound, focusing on case state access and defender assignment.


363-405: Validate spokesperson access in 'canDefenceUserAccessIndictmentCase'

The inclusion of the spokesperson access check allows civil claimant spokespersons to access indictment cases when appropriate. The condition ensures they cannot perform updates (!forUpdate), aligning with the PR objectives to restrict access to case files and generated PDFs.


22-26: Confirm the necessity of new imports

The imports of type User, UserRole, CivilClaimant, and Defendant are introduced. Ensure that these imported types and classes are utilized appropriately within the file and are necessary for the added logic.


Line range hint 427-450: Ensure 'forUpdate' parameter is propagated correctly in 'canUserAccessCase'

The addition of the forUpdate: boolean parameter to canUserAccessCase and its subsequent usage in role-specific functions enhances access control. Verify that all calls to canUserAccessCase include the forUpdate argument to maintain the intended permission checks.

Run the following script to find all usages of canUserAccessCase and check for the forUpdate parameter:

#!/bin/bash
# Description: Find all usages of 'canUserAccessCase' and check for 'forUpdate' parameter.

# Search for the function calls
rg --type typescript 'canUserAccessCase\(' -A 1

200-200: Confirm 'forUpdate' parameter usage in 'canPrisonStaffUserAccessCase'

The inclusion of the forUpdate: boolean parameter in canPrisonStaffUserAccessCase is appropriate to control update access. Ensure that all invocations of this function supply the forUpdate parameter to maintain consistent access control.

Run the following script to find all usages of canPrisonStaffUserAccessCase:

#!/bin/bash
# Description: Find all usages of 'canPrisonStaffUserAccessCase' and check for 'forUpdate' parameter.

# Search for the function calls
rg --type typescript 'canPrisonStaffUserAccessCase\(' -A 1

238-238: Verify 'forUpdate' parameter integration in 'canPrisonAdminUserAccessCase'

The addition of forUpdate: boolean to canPrisonAdminUserAccessCase helps manage update permissions effectively. Please confirm that all calls to this function include the forUpdate argument to avoid unintended access issues.

Use the following script to identify all calls to canPrisonAdminUserAccessCase:

#!/bin/bash
# Description: Find all usages of 'canPrisonAdminUserAccessCase' and check for 'forUpdate' parameter.

# Search for the function calls
rg --type typescript 'canPrisonAdminUserAccessCase\(' -A 1

33-33: Ensure 'forUpdate' parameter is consistently integrated

The addition of the forUpdate: boolean parameter to canProsecutionUserAccessCase enhances clarity regarding update permissions. Please verify that all calls to this function have been updated to include the new forUpdate argument to prevent any potential runtime errors.

Run the following script to locate all calls to canProsecutionUserAccessCase and check if they include the forUpdate parameter:

✅ Verification successful

'forUpdate' Parameter Correctly Integrated

All calls to canProsecutionUserAccessCase include the forUpdate parameter, ensuring consistency and preventing potential runtime errors.

  • apps/judicial-system/backend/src/app/modules/case/filters/case.filter.ts line 33
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of 'canProsecutionUserAccessCase' and check for 'forUpdate' parameter.

# Search for the function calls
rg --type typescript 'canProsecutionUserAccessCase\(' -A 1

Length of output: 95


Script:

#!/bin/bash
# Description: Find all usages of 'canProsecutionUserAccessCase' in .ts and .tsx files and check for 'forUpdate' parameter.

# Search for the function calls in TypeScript files
rg 'canProsecutionUserAccessCase\(' -g '*.ts' -g '*.tsx' -A 1

Length of output: 279

apps/judicial-system/backend/src/app/modules/case/limitedAccessCase.service.ts (3)

34-38: LGTM! Imports added appropriately

The added imports CivilClaimant, CivilClaimantService, Defendant, and DefendantService are necessary for the expanded functionality.


286-286: Dependency injection of CivilClaimantService

The CivilClaimantService is correctly injected into the constructor for use within the service.


510-510: Verify the updated file category filtering

The filtering logic in getAllFilesZip now uses defenderCaseFileCategoriesForRequestCases.includes(file.category). Ensure that this change aligns with the intended access permissions and that all necessary file categories are being included or excluded appropriately.

apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (1)

200-201: Verify the use of UserRole.DEFENDER for spokespersons

In the test cases for spokespersons, the user role is set to UserRole.DEFENDER. Please verify if this is intentional and aligns with the application's user role definitions. If a distinct role exists for spokespersons, it should be used to accurately reflect user permissions in the tests.

Run the following script to check for the existence of a UserRole.SPOKESPERSON or similar in the codebase:

This script searches for any user roles that include "Spokesperson" in their name. If such a role exists, consider updating the tests to use the appropriate user role.

Also applies to: 263-264, 330-331, 391-392

Copy link
Member

@unakb unakb left a comment

Choose a reason for hiding this comment

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

Looks good! 🙌 Nice separation of indictment case vs. request case logic 🤩

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 (5)
apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (5)

Line range hint 16-26: LGTM: New constant for defender case file categories in request cases

The new constant defenderCaseFileCategoriesForRequestCases is well-defined and contains appropriate categories for request cases. This improves code readability and maintainability.

Consider adding a brief comment explaining the purpose of this constant, e.g.:

// Defines the case file categories that a defender can access for request cases
export const defenderCaseFileCategoriesForRequestCases = [
  // ... (existing array items)
]

28-42: LGTM: New constants for defender case file categories in indictment cases

The introduction of defenderDefaultCaseFileCategoriesForIndictmentCases and defenderCaseFileCategoriesForIndictmentCases improves code organization and maintainability. The use of concat to create the extended list is appropriate.

Consider adding brief comments explaining the purpose of these constants, e.g.:

// Defines the default case file categories that a defender can access for indictment cases
const defenderDefaultCaseFileCategoriesForIndictmentCases = [
  // ... (existing array items)
]

// Defines all case file categories that a defender can access for indictment cases
const defenderCaseFileCategoriesForIndictmentCases =
  defenderDefaultCaseFileCategoriesForIndictmentCases.concat(
    // ... (existing array items)
  )

51-111: LGTM: New functions for checking defence user view permissions

The new functions canDefenceUserViewCaseFileOfRequestCase, canDefenceUserViewCaseFileOfIndictmentCase, and canDefenceUserViewCaseFile are well-structured and handle different scenarios appropriately. The logic for checking both defendants and civil claimants in indictment cases is correct.

Consider adding JSDoc comments to these functions to improve documentation, e.g.:

/**
 * Checks if a defence user can view a case file for a request case.
 * @param caseState - The current state of the case
 * @param caseFileCategory - The category of the case file
 * @returns True if the user can view the file, false otherwise
 */
const canDefenceUserViewCaseFileOfRequestCase = (
  // ... (existing function body)
)

// Add similar JSDoc comments for the other two functions

113-131: LGTM: New functions for checking prison staff and admin view permissions

The new functions canPrisonStaffUserViewCaseFile and canPrisonAdminUserViewCaseFile are well-implemented and consistent with the existing pattern of checking completed cases and specific file categories.

Consider adding JSDoc comments to these functions to improve documentation, similar to the suggestion for the defence user functions. Also, consider extracting the common logic of checking for completed cases into a separate function to reduce duplication, e.g.:

const isCompletedCaseWithCategory = (
  caseState: CaseState,
  caseFileCategory: CaseFileCategory,
  allowedCategories: CaseFileCategory[]
) => isCompletedCase(caseState) && allowedCategories.includes(caseFileCategory)

const canPrisonStaffUserViewCaseFile = (
  caseState: CaseState,
  caseFileCategory: CaseFileCategory,
) => isCompletedCaseWithCategory(caseState, caseFileCategory, prisonStaffCaseFileCategories)

// Similar change for canPrisonAdminUserViewCaseFile

146-161: LGTM: Updated canLimitedAccessUserViewCaseFile function body

The changes to the canLimitedAccessUserViewCaseFile function body improve code organization by delegating specific checks to helper functions. The new logic correctly handles different user types and passes the necessary parameters.

Consider using early returns to simplify the function structure and improve readability:

export const canLimitedAccessUserViewCaseFile = (
  user: User,
  caseType: CaseType,
  caseState: CaseState,
  caseFileCategory?: CaseFileCategory,
  defendants?: Defendant[],
  civilClaimants?: CivilClaimant[],
) => {
  if (!caseFileCategory) {
    return false
  }

  if (isDefenceUser(user)) {
    return canDefenceUserViewCaseFile(
      user.nationalId,
      caseType,
      caseState,
      caseFileCategory,
      defendants,
      civilClaimants,
    )
  }

  if (isPrisonStaffUser(user)) {
    return canPrisonStaffUserViewCaseFile(caseState, caseFileCategory)
  }

  if (isPrisonAdminUser(user)) {
    return canPrisonAdminUserViewCaseFile(caseState, caseFileCategory)
  }

  return false
}

This structure eliminates the need for the final return false statement and makes the function's flow easier to follow.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 972e8d2 and b8af785.

📒 Files selected for processing (4)
  • apps/judicial-system/backend/src/app/modules/case/interceptors/limitedAccessCaseFile.interceptor.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts (2 hunks)
  • apps/judicial-system/backend/src/app/modules/file/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/judicial-system/backend/src/app/modules/case/interceptors/limitedAccessCaseFile.interceptor.ts
  • apps/judicial-system/backend/src/app/modules/file/guards/limitedAccessViewCaseFile.guard.ts
  • apps/judicial-system/backend/src/app/modules/file/index.ts
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.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 (2)
📓 Common learnings
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts:1-1
Timestamp: 2024-10-17T11:30:12.482Z
Learning: The usage of `defenderRule` in the following test files is intentional and should remain unchanged:

- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createPresignedPostRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/deleteCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/getCaseFileSignedUrlRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRulingPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRequestPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCourtRecordPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getByIdRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getAllFilesZipRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/caseController/getAllRolesRules.spec.ts`
apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (2)
Learnt from: oddsson
PR: island-is/island.is#16138
File: apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts:74-87
Timestamp: 2024-10-08T15:39:04.351Z
Learning: User prefers to keep similar conditional statements separate rather than combining them into a single conditional with logical operators.
Learnt from: oddsson
PR: island-is/island.is#16138
File: apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts:74-87
Timestamp: 2024-09-24T20:55:56.753Z
Learning: User prefers to keep similar conditional statements separate rather than combining them into a single conditional with logical operators.
🔇 Additional comments (2)
apps/judicial-system/backend/src/app/modules/file/guards/caseFileCategory.ts (2)

14-14: LGTM: New import added for CivilClaimant and Defendant

The new import statement for CivilClaimant and Defendant from '../../defendant' is correctly added and necessary for the new functions using these types.


133-139: LGTM: Updated function signature for canLimitedAccessUserViewCaseFile

The function signature for canLimitedAccessUserViewCaseFile has been appropriately updated to include defendants and civilClaimants parameters. These new parameters are necessary for the updated logic in the function body and their types are consistent with the imports and usage.

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 (3)
apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (3)

225-288: Well-structured test cases for access restrictions

These test cases effectively cover the scenarios where defenders and spokespersons should not have access to certain case file categories in indictment cases. The structure is clear and consistent with the previous test cases.

One minor suggestion for consistency:

Consider updating the describe block descriptions to match the style used in the previous segment:

-          describe('a defender with case files access can not view', () => {
+          describe('a defender with case files access cannot view', () => {
-          describe('spokesperson with case files access can not view', () => {
+          describe('spokesperson with case files access cannot view', () => {

This change would make the test descriptions more consistent throughout the file.


359-413: Well-implemented test cases for access restrictions

These test cases effectively cover the scenarios where defenders and spokespersons without case files access should not be able to view certain case file categories in indictment cases. The structure is clear and consistent with the previous test cases.

For consistency with earlier suggestions:

Consider updating the describe block descriptions:

-          describe('a defender without case files access can not view', () => {
+          describe('a defender without case files access cannot view', () => {
-          describe('spokesperson without case files access can not view', () => {
+          describe('spokesperson without case files access cannot view', () => {

This change would improve consistency throughout the test file.


Line range hint 1-713: Comprehensive and well-structured test suite expansion

The additions to this test file significantly enhance the coverage of the LimitedAccessViewCaseFileGuard, particularly for defenders and spokespersons in various scenarios. The new test cases align well with the PR objectives of enhancing access for civil claimants' spokespersons while maintaining appropriate restrictions.

The structure of the test suite is consistent and easy to follow, with clear descriptions for each test case. The use of nested describe blocks effectively organizes the tests by case type, state, and user role.

For future consideration:

As the test suite grows, consider extracting some of the common setup logic (like creating mock requests) into helper functions to reduce repetition and improve maintainability. This could make the test file even more readable and easier to maintain in the long run.

Overall, excellent work on improving the test coverage and maintaining a clear, consistent structure throughout this complex test suite.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b8af785 and a4a3160.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.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 (2)
📓 Common learnings
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts:1-1
Timestamp: 2024-10-17T11:30:12.482Z
Learning: The usage of `defenderRule` in the following test files is intentional and should remain unchanged:

- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createPresignedPostRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/deleteCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/getCaseFileSignedUrlRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRulingPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRequestPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCourtRecordPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getByIdRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getAllFilesZipRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/caseController/getAllRolesRules.spec.ts`
apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (3)
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts:175-185
Timestamp: 2024-10-17T11:53:19.983Z
Learning: In the Jest tests for the `LimitedAccessViewCaseFileGuard` in `apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts`, code duplication in the `beforeEach` blocks is acceptable and should remain unchanged.
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCaseFilesRecordPdfRolesRules.spec.ts:1-1
Timestamp: 2024-10-17T11:30:12.482Z
Learning: The usage of `defenderRule` in the following test files is intentional and should remain unchanged:

- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createPresignedPostRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/deleteCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/createCaseFileRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/file/test/limitedAccessFileController/getCaseFileSignedUrlRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRulingPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getRequestPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getCourtRecordPdfRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getByIdRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getAllFilesZipRolesRules.spec.ts`
- `apps/judicial-system/backend/src/app/modules/case/test/caseController/getAllRolesRules.spec.ts`
Learnt from: gudjong
PR: island-is/island.is#16389
File: apps/judicial-system/backend/src/app/modules/case/test/limitedAccessCaseController/getIndictmentPdfGuards.spec.ts:24-25
Timestamp: 2024-10-17T11:41:45.565Z
Learning: In certain scenarios within the judicial-system backend, the `RolesGuard` may intentionally follow the `CaseExistsGuard` when specific roles rules require the guard order to be reversed, as seen in tests like `getIndictmentPdfGuards.spec.ts`.
🔇 Additional comments (2)
apps/judicial-system/backend/src/app/modules/file/guards/test/limitedAccessViewCaseFileGuard.spec.ts (2)

169-223: Excellent addition of test cases for defenders and spokespersons with case files access

These new test cases significantly improve the coverage of the LimitedAccessViewCaseFileGuard for indictment cases. They properly test the scenarios where defenders and spokespersons have access to case files, which aligns well with the PR objectives of enhancing access for civil claimants' spokespersons.

The test structure is clear and consistent, making it easy to understand the different scenarios being tested. Good job on including the nationalId in the mock requests, as it allows for more specific user identification.


292-349: Comprehensive test coverage for limited access scenarios

These test cases are a valuable addition, covering the scenarios where defenders and spokespersons without full case files access can still view specific categories (COURT_RECORD and RULING) in indictment cases. This aligns well with the PR objectives of implementing restrictions on access to case files while still allowing necessary access.

The test structure is consistent with previous sections, and the mock requests are correctly set up to reflect the limited access scenarios. Good job on maintaining clarity and consistency throughout these complex test cases.

@gudjong gudjong added the automerge Merge this PR as soon as all checks pass label Oct 18, 2024
@kodiakhq kodiakhq bot merged commit d6b0e01 into main Oct 18, 2024
201 checks passed
@kodiakhq kodiakhq bot deleted the j-s/spokesperson-access branch October 18, 2024 12:59
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