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): Service Certificate to Court #17904

Merged
merged 5 commits into from
Feb 14, 2025

Conversation

gudjong
Copy link
Member

@gudjong gudjong commented Feb 10, 2025

Service Certificate to Court

Skila birtingavottorði í Auði + bæta við verjanda upplýsingum

What

  • Delivers service certificates for successfully served subpoenas to court after arraignment completion.

Why

  • The court wants to receive the service certificates.

Screenshots / Gifs

image

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
    • Improved service certificate presentation with enhanced PDF layout including increased margins, refined headings, and adjusted spacing.
    • Enhanced display of defendant details with better formatting and clear indication of defense preferences.
    • Added functionality for delivering service certificates to court, accompanied by automated messaging notifications to improve tracking.
    • Introduced a new method for delivering service certificates to the court within the subpoena management system.

@gudjong gudjong requested a review from a team as a code owner February 10, 2025 17:27
Copy link
Contributor

coderabbitai bot commented Feb 10, 2025

Walkthrough

This pull request introduces modifications to the service certificate PDF generation, delivery, and messaging workflow within the judicial system backend. The changes update the PDF formatting and defendant information presentation, add a method for sending messages related to indictment arraignment completion, implement new delivery endpoints in both controller and service layers, and extend the messaging enum and endpoint. New test suites also verify the functionality and guard configurations of the added methods.

Changes

File(s) Change Summary
apps/judicial-system/backend/src/app/formatters/serviceCertificatePdf.ts Updated createServiceCertificate: increased top margin (40 → 80), replaced addHugeHeading with addLargeHeading, adjusted empty line counts, updated date format (PPpPPPp), added defendant info variables, and integrated defender choice logic. New imports added.
apps/judicial-system/backend/src/app/modules/case/case.service.ts Added new method addMessagesForIndictmentArraignmentCompletionToQueue that sends messages (of type DELIVERY_TO_COURT_SERVICE_CERTIFICATE) upon indictment arraignment completion; modified update to trigger this when indictmentDecision is added.
apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts
.../subpoena/subpoena.service.ts
Introduced deliverServiceCertificateToCourt in the controller and service to handle POST requests for delivering service certificates, generating PDFs, and uploading them to the court system.
apps/judicial-system/backend/src/app/modules/subpoena/test/internalSubpoenaController/deliverServiceCertificateToCourt*.spec.ts Added test suites for the deliverServiceCertificateToCourt functionality, including tests for proper method invocation and guard configurations.
libs/judicial-system/message/src/lib/message.ts Extended messaging: added DELIVERY_TO_COURT_SERVICE_CERTIFICATE to the MessageType enum and updated the messageEndpoint object with the corresponding endpoint.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant ISC as InternalSubpoenaController
    participant SS as SubpoenaService
    participant PS as PdfService
    participant CS as CourtService

    C->>ISC: POST deliver service certificate
    ISC->>SS: deliverServiceCertificateToCourt(params)
    SS->>PS: getServiceCertificatePdf(case, defendant, subpoena)
    PS-->>SS: PDF document
    SS->>CS: createDocument(fileName, PDF)
    CS-->>SS: Delivery result
    SS-->>ISC: DeliverResponse
    ISC-->>C: Response
Loading
sequenceDiagram
    participant CSvc as CaseService
    participant MQ as MessageQueue
    participant D as Defendant

    CSvc->>CSvc: update(case)
    alt indictmentDecision added
        CSvc->>CSvc: addMessagesForIndictmentArraignmentCompletionToQueue(case, user)
        loop For each Defendant
            CSvc->>D: check serviceStatus
            alt Successful service (defender/electronic/in-person)
                CSvc->>MQ: send DELIVERY_TO_COURT_SERVICE_CERTIFICATE message
            end
        end
    end
Loading

Possibly related PRs

  • chore(j-s): Show user role in service certificate #16594: The changes in the main PR are related to the modifications made to the createServiceCertificate function in the serviceCertificatePdf.ts file, as both PRs involve updates to this function, albeit for different purposes.
  • feat(j-s): Subpoena PDF #15201: The changes in the main PR, specifically the modifications to the createServiceCertificate function in serviceCertificatePdf.ts, are related to the changes in the retrieved PR, which introduces the createSubpoenaPDF function in subpoenaPdf.ts, as both involve the creation of PDF documents with similar formatting functions and structures.
  • feat(j-s): Deliver Subpoena to Court #17239: The changes in the main PR, which focus on enhancing the createServiceCertificate function for generating service certificates, are related to the retrieved PR as both involve modifications to the handling of service certificates, specifically in the context of delivering them to the court. Both PRs introduce new methods and logic that enhance the functionality surrounding service certificates.

Suggested labels

automerge

Suggested reviewers

  • unakb
  • thorhildurt
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

nx-cloud bot commented Feb 10, 2025

View your CI Pipeline Execution ↗ for commit 466d59d.

Command Status Duration Result
nx run-many --projects judicial-system-backend ... ✅ Succeeded 22m 33s View ↗
nx run-many --target=build --projects=judicial-... ✅ Succeeded 38s View ↗
nx run-many --target=build --projects=judicial-... ✅ Succeeded 19s View ↗
nx run-many --projects judicial-system-message,... ✅ Succeeded 1s View ↗
nx run-many --target=lint --projects=judicial-s... ✅ Succeeded 8s View ↗
nx run-many --target=codegen/frontend-client --... ✅ Succeeded 13s View ↗
nx run-many --target=codegen/backend-schema --a... ✅ Succeeded 54s View ↗

☁️ Nx Cloud last updated this comment at 2025-02-14 11:58:37 UTC

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/judicial-system/backend/src/app/modules/subpoena/test/internalSubpoenaController/deliverServiceCertificateToCourt.spec.ts (1)

79-112: Add test cases for error scenarios.

While error handling is set up in the mocks, there are no test cases verifying the behavior when PDF generation or document creation fails.

Consider adding these test cases:

 describe('service certificate delivered to court', () => {
   // ... existing test ...
 })
+
+describe('when PDF generation fails', () => {
+  let then: Then
+
+  beforeEach(async () => {
+    const mockGetServiceCertificatePdf = mockPdfService.getServiceCertificatePdf as jest.Mock
+    mockGetServiceCertificatePdf.mockRejectedValue(new Error('PDF generation failed'))
+
+    then = await givenWhenThen()
+  })
+
+  it('should propagate the error', () => {
+    expect(then.error).toBeInstanceOf(Error)
+    expect(then.error.message).toBe('PDF generation failed')
+  })
+})
+
+describe('when court document creation fails', () => {
+  let then: Then
+
+  beforeEach(async () => {
+    const mockGetServiceCertificatePdf = mockPdfService.getServiceCertificatePdf as jest.Mock
+    mockGetServiceCertificatePdf.mockResolvedValue('pdf-content')
+    const mockCreateDocument = mockCourtService.createDocument as jest.Mock
+    mockCreateDocument.mockRejectedValue(new Error('Document creation failed'))
+
+    then = await givenWhenThen()
+  })
+
+  it('should propagate the error', () => {
+    expect(then.error).toBeInstanceOf(Error)
+    expect(then.error.message).toBe('Document creation failed')
+  })
+})
apps/judicial-system/backend/src/app/formatters/serviceCertificatePdf.ts (1)

142-149: Extract indentation logic into a helper function.

The comment suggests this indentation logic should be moved to a helper function for reusability and consistency.

Consider adding this helper:

+const addIndentedText = (
+  doc: PDFKit.PDFDocument,
+  text: string,
+  labelWidth: number,
+  options?: { newLine?: boolean }
+) => {
+  doc.text(text, 50 + labelWidth, doc.y + 5)
+  if (options?.newLine) {
+    doc.text('', 50)
+  }
+}
+
 // Consider adding indentation to helper functions
-doc.text(
-  ` ${defendant.address ?? 'Ekki skráð'}`,
-  50 + doc.widthOfString(defendantLabel),
-  doc.y + 5,
-)
-doc.text('', 50)
+addIndentedText(doc, ` ${defendant.address ?? 'Ekki skráð'}`, doc.widthOfString(defendantLabel), { newLine: true })
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0f80b3e and 424b9b9.

📒 Files selected for processing (7)
  • apps/judicial-system/backend/src/app/formatters/serviceCertificatePdf.ts (8 hunks)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (4 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/test/internalSubpoenaController/deliverServiceCertificateToCourt.spec.ts (1 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/test/internalSubpoenaController/deliverServiceCertificateToCourtGuards.spec.ts (1 hunks)
  • libs/judicial-system/message/src/lib/message.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`apps/**/*`: "Confirm that the code adheres to the following...

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/internalSubpoenaController/deliverServiceCertificateToCourt.spec.ts
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts
  • apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts
  • apps/judicial-system/backend/src/app/modules/subpoena/test/internalSubpoenaController/deliverServiceCertificateToCourtGuards.spec.ts
  • apps/judicial-system/backend/src/app/formatters/serviceCertificatePdf.ts
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts
`libs/**/*`: "Confirm that the code adheres to the following...

libs/**/*: "Confirm that the code adheres to the following:

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
  • libs/judicial-system/message/src/lib/message.ts
🧠 Learnings (2)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1)
Learnt from: unakb
PR: island-is/island.is#16393
File: apps/judicial-system/digital-mailbox-api/src/app/modules/cases/models/subpoena.response.ts:164-169
Timestamp: 2024-11-12T15:15:11.835Z
Learning: Ensure that suggested code changes in `subpoena.response.ts` are accurate and necessary, avoiding redundant suggestions.
apps/judicial-system/backend/src/app/modules/subpoena/test/internalSubpoenaController/deliverServiceCertificateToCourtGuards.spec.ts (2)
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-11-12T15:15:11.835Z
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`.
Learnt from: oddsson
PR: island-is/island.is#16463
File: apps/judicial-system/backend/src/app/modules/subpoena/test/limitedAccessSubpoenaController/limitedAccessSubpoenaControllerGuards.spec.ts:17-17
Timestamp: 2024-11-12T15:15:20.158Z
Learning: In `LimitedAccessSubpoenaController`, `SubpoenaExistsOptionalGuard` is still used on specific endpoints not covered by the test file `limitedAccessSubpoenaControllerGuards.spec.ts`.
🪛 Biome (1.9.4)
apps/judicial-system/backend/src/app/formatters/serviceCertificatePdf.ts

[error] 214-215: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: linting (judicial-system-backend,judicial-system-message,judicial-system-message-handler,judicial...
  • GitHub Check: formatting
  • GitHub Check: build (judicial-system-message-handler,judicial-system-scheduler)
  • GitHub Check: tests (judicial-system-message,judicial-system-message-handler,judicial-system-scheduler)
  • GitHub Check: tests (judicial-system-backend)
🔇 Additional comments (6)
apps/judicial-system/backend/src/app/modules/subpoena/test/internalSubpoenaController/deliverServiceCertificateToCourtGuards.spec.ts (1)

8-29: LGTM! The guard configuration test is thorough and well-structured.

The test effectively verifies both the presence and order of all required guards, ensuring proper access control and data validation.

libs/judicial-system/message/src/lib/message.ts (1)

15-15: LGTM! The message type and endpoint are properly defined.

The new message type and endpoint follow the established naming pattern and correctly map to the controller method.

Also applies to: 58-58

apps/judicial-system/backend/src/app/modules/subpoena/internalSubpoena.controller.ts (1)

165-199: LGTM! Implementation follows established patterns.

The new endpoint for delivering service certificates to court is well-implemented with:

  • Proper authorization guards
  • Consistent parameter handling
  • Standard response type
  • Appropriate debug logging
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1)

434-467: LGTM! Robust error handling and consistent implementation.

The service certificate delivery implementation:

  • Follows established error handling patterns
  • Uses consistent file naming
  • Provides appropriate logging
apps/judicial-system/backend/src/app/modules/case/case.service.ts (2)

1404-1432: LGTM! Correctly handles service certificate message generation.

The method properly:

  • Filters for successfully served subpoenas
  • Uses appropriate message type for service certificate delivery
  • Follows message queue patterns

1645-1651: LGTM! Appropriate trigger for service certificate delivery.

The changes correctly trigger service certificate delivery when:

  • An indictment decision is newly set
  • The arraignment is completed

…:island-is/island.is into j-s/deliver-service-certificate-to-court
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

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

1363-1363: Simplify the subpoena comparison logic.

The subpoena comparison can be simplified using optional chaining and nullish coalescing.

-          )?.subpoenas?.[0]?.id !== updatedDefendant.subpoenas?.[0]?.id, // Only deliver new subpoenas
+          )?.subpoenas?.[0]?.id ?? null !== updatedDefendant.subpoenas?.[0]?.id ?? null, // Only deliver new subpoenas
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 424b9b9 and 466d59d.

📒 Files selected for processing (2)
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts (4 hunks)
  • apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`apps/**/*`: "Confirm that the code adheres to the following...

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
  • apps/judicial-system/backend/src/app/modules/case/case.service.ts
🔇 Additional comments (3)
apps/judicial-system/backend/src/app/modules/subpoena/subpoena.service.ts (1)

435-468: LGTM! Well-structured implementation of service certificate delivery.

The implementation follows the established patterns in the codebase, with proper error handling and logging.

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

1413-1420: Consider creating a helper function for service status check.

The service status check logic could be extracted into a helper function for better readability and reusability.

+  private isSuccessfulServiceStatus(serviceStatus: ServiceStatus | undefined): boolean {
+    return Boolean(serviceStatus && [
+      ServiceStatus.DEFENDER,
+      ServiceStatus.ELECTRONICALLY,
+      ServiceStatus.IN_PERSON,
+    ].includes(serviceStatus))
+  }
+
   private addMessagesForIndictmentArraignmentCompletionToQueue(
     theCase: Case,
     user: TUser,
   ): Promise<void> {
     const messages: Message[] = []

     theCase.defendants?.forEach((defendant) => {
       const subpoena = defendant.subpoenas?.[0]

-      const hasSubpoenaBeenSuccessfullyServedToDefendant =
-        subpoena?.serviceStatus &&
-        [
-          ServiceStatus.DEFENDER,
-          ServiceStatus.ELECTRONICALLY,
-          ServiceStatus.IN_PERSON,
-        ].includes(subpoena.serviceStatus)
+      const hasSubpoenaBeenSuccessfullyServedToDefendant = 
+        this.isSuccessfulServiceStatus(subpoena?.serviceStatus)

1646-1652: LGTM! Clear and concise indictment decision check.

The condition for triggering the service certificate delivery is clear and follows the pattern of other message queue triggers in the codebase.

@gudjong gudjong added this pull request to the merge queue Feb 14, 2025
Merged via the queue into main with commit 320b7e6 Feb 14, 2025
32 checks passed
@gudjong gudjong deleted the j-s/deliver-service-certificate-to-court branch February 14, 2025 17:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants