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): Store Subpoena PDF and HASH #16235

Merged
merged 3 commits into from
Oct 3, 2024
Merged

feat(j-s): Store Subpoena PDF and HASH #16235

merged 3 commits into from
Oct 3, 2024

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Oct 2, 2024

Store Subpoena PDF and HASH

Vista fyrirkall í S3 og MD5 fyrir fyrirkallið

What

  • Stores generated subpoenas in S3 and its has in the DB.

Why

  • To be able to verify subpoenas.

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

    • Added a new hash column to the subpoena table for better data integrity.
    • Enhanced PDF generation for subpoenas by incorporating confirmation details.
    • Introduced a method to update the hash of a subpoena in the service.
  • Bug Fixes

    • Improved error handling and messaging for subpoena retrieval.
  • Documentation

    • Updated API documentation to reflect the new optional hash property in the Subpoena model.

@gudjong gudjong requested a review from a team as a code owner October 2, 2024 11:05
Copy link
Contributor

coderabbitai bot commented Oct 2, 2024

Walkthrough

This pull request introduces changes to the management of subpoenas in the judicial system application. A new migration file is added to update the subpoena table by adding a hash column. The createSubpoena function in the PDF formatter is modified to accept a new confirmation parameter. The PdfService class is updated to incorporate the SubpoenaService, enhancing PDF generation and hash management for subpoenas. Additionally, guards and models are updated to reflect these changes, ensuring better handling of subpoena data.

Changes

File Path Change Summary
.../migrations/20241002084126-update-subpoena.js Added migration to add hash column to subpoena table with up and down methods.
.../formatters/subpoenaPdf.ts Updated createSubpoena function to include new confirmation parameter and adjust logic.
.../modules/case/pdf.service.ts Modified PdfService to include SubpoenaService, updated getSubpoenaPdf method logic.
.../modules/subpoena/guards/subpoenaExists.guard.ts Adjusted logic in SubpoenaExistsGuard for handling subpoenaId and defendant checks.
.../modules/subpoena/models/subpoena.model.ts Added optional hash property to Subpoena class.
.../modules/subpoena/subpoena.service.ts Introduced setHash method in SubpoenaService for updating subpoena hash and error handling.

Possibly related PRs

Suggested labels

automerge

Suggested reviewers

  • unakb

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (9)
apps/judicial-system/backend/migrations/20241002084126-update-subpoena.js (2)

1-1: Remove redundant 'use strict' directive

The 'use strict' directive is unnecessary in this context as JavaScript modules are automatically in strict mode.

Apply this change to remove the redundant directive:

-'use strict'
🧰 Tools
🪛 Biome

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


1-22: Overall implementation aligns well with PR objectives

This migration file successfully implements the database changes required for storing subpoena hashes:

  • Adds a 'hash' column to the 'subpoena' table
  • Provides a method to revert the changes if needed
  • Uses transactions to ensure data integrity

The implementation aligns perfectly with the PR objective of "storing generated subpoenas in Amazon S3 and saving their corresponding MD5 hashes in the database."

Consider adding an index to the 'hash' column if you plan to perform frequent lookups using this field. This can be done in a separate migration if needed.

🧰 Tools
🪛 Biome

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

apps/judicial-system/backend/src/app/modules/subpoena/guards/subpoenaExists.guard.ts (2)

27-30: Approved with a suggestion for error handling

The changes improve the guard's functionality by handling the case when defendant is not present. The added comment enhances code readability.

However, consider adding error handling for the case where findBySubpoenaId doesn't find a subpoena:

const subpoena = await this.subpoenaService.findBySubpoenaId(subpoenaId);
if (!subpoena) {
  throw new NotFoundException(`Subpoena with ID ${subpoenaId} not found`);
}
request.subpoena = subpoena;

This ensures consistent error handling across different scenarios.


Line range hint 33-43: Approved with a suggestion for type safety

The changes improve the guard's functionality and error handling. The added comment and more specific error message enhance code readability and debugging.

To further improve type safety, consider adding a type guard for the subpoena:

const subpoena = defendant.subpoenas?.find(
  (s): s is NonNullable<typeof s> => s.id === subpoenaId
);

This ensures that subpoena is correctly typed as non-null when found, which aligns with TypeScript best practices.

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

80-82: LGTM! Consider a more specific property name.

The addition of the hash property aligns well with the PR objective of storing MD5 hashes for subpoenas. The implementation is consistent with the rest of the file and follows TypeScript best practices.

Consider using a more specific name for the property, such as md5Hash or subpoenaHash, to improve clarity and maintainability.

-  hash?: string
+  md5Hash?: string
apps/judicial-system/backend/src/app/formatters/subpoenaPdf.ts (1)

159-161: LGTM: Confirmation details added correctly.

The addition of the addConfirmation function call when confirmation is provided is correct and aligns with the PR objective. To improve clarity, consider adding a comment explaining the purpose of this block:

// Add confirmation details to the PDF if provided
if (confirmation) {
  addConfirmation(doc, confirmation)
}
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (2)

60-74: LGTM: New setHash method implemented correctly

The new setHash method aligns well with the PR objective of storing subpoena hashes. The error handling is comprehensive, covering cases of unexpected number of affected rows.

A minor suggestion for improvement:

Consider using a custom error message for the case when more than one row is affected, similar to how you're handling the case of no affected rows. This would provide more specific information about the nature of the error.

 if (numberOfAffectedRows > 1) {
-  // Tolerate failure, but log error
-  this.logger.error(
-    `Unexpected number of rows (${numberOfAffectedRows}) affected when updating subpoena hash for subpoena ${id}`,
-  )
+  throw new InternalServerErrorException(`Unexpected number of rows (${numberOfAffectedRows}) affected when updating subpoena hash for subpoena ${id}`)
 } else if (numberOfAffectedRows < 1) {
   throw new InternalServerErrorException(`Could not update subpoena ${id}`)
 }

This change would make the error handling more consistent and provide more detailed information in case of an unexpected state.


Line range hint 1-185: Overall assessment: Changes align with PR objectives and improve code quality

The implementation of storing subpoena hashes has been successfully added, aligning with the PR objectives. Error handling and messaging have been improved, enhancing the overall robustness of the code.

To further improve consistency in error handling:

Consider adopting a uniform approach to error handling across the service. For instance, you might want to create custom exception classes for different types of errors (e.g., SubpoenaNotFoundException, SubpoenaUpdateException) and use them consistently throughout the service. This would make error handling more standardized and easier to manage as the codebase grows.

Example:

export class SubpoenaNotFoundException extends NotFoundException {
  constructor(subpoenaId: string) {
    super(`Subpoena with subpoena id ${subpoenaId} not found`);
  }
}

export class SubpoenaUpdateException extends InternalServerErrorException {
  constructor(subpoenaId: string, affectedRows: number) {
    super(`Unexpected number of rows (${affectedRows}) affected when updating subpoena ${subpoenaId}`);
  }
}

These custom exceptions could then be used in your methods, providing a more consistent and maintainable approach to error handling.

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

304-304: Redundant assignment to undefined

The variable confirmation is explicitly initialized to undefined, which is unnecessary since variables declared with let are undefined by default.

Consider simplifying the declaration:

-let confirmation: Confirmation | undefined = undefined
+let confirmation: Confirmation | undefined
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4d38b65 and 7fb75aa.

📒 Files selected for processing (6)
  • apps/judicial-system/backend/migrations/20241002084126-update-subpoena.js (1 hunks)
  • apps/judicial-system/backend/src/app/formatters/subpoenaPdf.ts (4 hunks)
  • apps/judicial-system/backend/src/app/modules/case/pdf.service.ts (4 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/guards/subpoenaExists.guard.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/models/subpoena.model.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
apps/judicial-system/backend/migrations/20241002084126-update-subpoena.js (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/formatters/subpoenaPdf.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/pdf.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/subpoena/guards/subpoenaExists.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/subpoena/models/subpoena.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/subpoena/subpoena.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."
🪛 Biome
apps/judicial-system/backend/migrations/20241002084126-update-subpoena.js

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (12)
apps/judicial-system/backend/migrations/20241002084126-update-subpoena.js (2)

4-13: LGTM: up method implementation

The up method is well-implemented:

  • Uses a transaction for atomicity
  • Adds the 'hash' column as described in the PR objectives
  • Allows null values, which is appropriate for existing records
  • Follows Sequelize migration best practices

15-21: LGTM: down method implementation

The down method is correctly implemented:

  • Uses a transaction for atomicity
  • Properly reverses the action of the up method by removing the 'hash' column
  • Follows Sequelize migration best practices
apps/judicial-system/backend/src/app/modules/subpoena/guards/subpoenaExists.guard.ts (1)

Line range hint 1-63: Overall assessment: Improvements in guard functionality and error handling

The changes to the SubpoenaExistsGuard class enhance its functionality by:

  1. Handling cases where the defendant is not present.
  2. Improving error messages for better debugging and user feedback.
  3. Adding clarifying comments to explain the context of subpoenaId.

These modifications adhere to NextJS and TypeScript best practices, improving the overall code quality and maintainability. The guard now provides more robust checking for subpoena existence across different scenarios.

Consider implementing the suggested improvements for error handling and type safety to further enhance the code.

apps/judicial-system/backend/src/app/formatters/subpoenaPdf.ts (4)

25-25: LGTM: Import statement updated correctly.

The Confirmation type has been added to the import statement from pdfHelpers. This addition is necessary for the new confirmation parameter in the createSubpoena function.


37-37: LGTM: Function signature updated correctly.

The createSubpoena function signature has been updated to include the new optional parameter confirmation of type Confirmation. This change maintains backward compatibility while allowing for the new functionality.


56-58: Please clarify the purpose of adding empty lines.

A new conditional block has been added to insert 5 empty lines when confirmation is provided. Could you please explain the reasoning behind this layout adjustment? It might be helpful to add a comment explaining why these empty lines are necessary when a confirmation is present.


Line range hint 37-167: LGTM: Changes align with PR objective and maintain code integrity.

The modifications to the createSubpoena function successfully implement the new confirmation functionality while maintaining the integrity of the existing code. The changes are minimal and focused, aligning well with the PR objective.

To ensure the changes don't introduce any regressions:

Please review the output to ensure all calls to createSubpoena are updated correctly if needed, or confirm that existing calls don't need modification due to the optional nature of the new parameter.

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

5-10: LGTM: Import statements updated correctly

The addition of InternalServerErrorException to the import statement is appropriate for the new error handling in the setHash method.


138-138: LGTM: Improved error message clarity

The update to the error message in the findBySubpoenaId method enhances clarity by specifying "subpoena id" instead of just "id". This change improves the readability and specificity of error messages, which is a good practice.

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

5-5: Correctly importing forwardRef

The addition of forwardRef from @nestjs/common is appropriate for handling circular dependencies during dependency injection.


37-37: Properly importing Subpoena and SubpoenaService

Importing Subpoena and SubpoenaService from '../subpoena' is necessary for the added functionality related to subpoenas.


49-50: Using forwardRef for SubpoenaService injection

Utilizing @Inject(forwardRef(() => SubpoenaService)) ensures that circular dependencies are correctly managed when injecting SubpoenaService into PdfService.

Copy link

codecov bot commented Oct 2, 2024

Codecov Report

Attention: Patch coverage is 16.12903% with 26 lines in your changes missing coverage. Please review.

Project coverage is 36.76%. Comparing base (0e26000) to head (4fc0159).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...system/backend/src/app/modules/case/pdf.service.ts 15.78% 16 Missing ⚠️
...ckend/src/app/modules/subpoena/subpoena.service.ts 12.50% 7 Missing ⚠️
...l-system/backend/src/app/formatters/subpoenaPdf.ts 0.00% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16235      +/-   ##
==========================================
- Coverage   36.93%   36.76%   -0.17%     
==========================================
  Files        6781     6787       +6     
  Lines      139980   139935      -45     
  Branches    39802    39800       -2     
==========================================
- Hits        51699    51449     -250     
- Misses      88281    88486     +205     
Flag Coverage Δ
api 3.37% <ø> (ø)
application-system-api 41.64% <ø> (ø)
application-ui-shell 21.29% <ø> (ø)
judicial-system-backend 55.24% <16.12%> (-0.05%) ⬇️

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

Files with missing lines Coverage Δ
...pp/modules/subpoena/guards/subpoenaExists.guard.ts 19.23% <ø> (ø)
.../src/app/modules/subpoena/models/subpoena.model.ts 82.60% <100.00%> (+0.79%) ⬆️
...l-system/backend/src/app/formatters/subpoenaPdf.ts 10.93% <0.00%> (+0.48%) ⬆️
...ckend/src/app/modules/subpoena/subpoena.service.ts 33.33% <12.50%> (-3.93%) ⬇️
...system/backend/src/app/modules/case/pdf.service.ts 68.93% <15.78%> (-8.26%) ⬇️

... and 49 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 0e26000...4fc0159. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 2, 2024

Datadog Report

Branch report: j-s/subpoena-hash
Commit report: 5b0f6e5
Test service: judicial-system-backend

✅ 0 Failed, 21238 Passed, 0 Skipped, 18m 54.73s Total Time
🔻 Test Sessions change in coverage: 1 decreased (-0.05%)

🔻 Code Coverage Decreases vs Default Branch (1)

@oddsson oddsson added automerge Merge this PR as soon as all checks pass and removed automerge Merge this PR as soon as all checks pass labels Oct 2, 2024
@gudjong gudjong added the automerge Merge this PR as soon as all checks pass label Oct 2, 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: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7fb75aa and d961efc.

📒 Files selected for processing (1)
  • apps/judicial-system/backend/src/app/modules/case/pdf.service.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/judicial-system/backend/src/app/modules/case/pdf.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."
🔇 Additional comments (3)
apps/judicial-system/backend/src/app/modules/case/pdf.service.ts (3)

5-5: LGTM: Import statements updated correctly

The import statements have been updated to include the necessary dependencies for the new subpoena functionality. The addition of forwardRef suggests proper handling of potential circular dependencies, which is a good practice in NextJS applications.

Also applies to: 37-37


49-50: LGTM: Proper dependency injection for SubpoenaService

The SubpoenaService is correctly injected using forwardRef, which is the recommended approach for handling circular dependencies in NextJS applications. This addresses the previous question about why forwardRef is used here and not for other services like UserService. It's likely that there's a circular dependency between PdfService and SubpoenaService.


301-306: LGTM: Method signature updated for flexibility

The getSubpoenaPdf method signature has been updated to include optional parameters, allowing for more flexible use. This change supports both new subpoena creation and existing subpoena retrieval, which aligns well with the PR objectives. The use of optional parameters is a good TypeScript practice, enhancing type safety.

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