Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix(licenses): pkpass status on machine license #16679

Merged
merged 14 commits into from
Nov 6, 2024

Conversation

thorkellmani
Copy link
Member

@thorkellmani thorkellmani commented Oct 31, 2024

What

  • Check expiration date for machine license pk pass status availability

Why

  • Shouldn't get machine license if expired

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 license validity checks with improved expiration date logic.
    • Introduced a streamlined date comparison method for better accuracy.
  • Bug Fixes

    • Resolved issues with license availability checks by ensuring proper validation of expiration dates.
  • Refactor

    • Removed the outdated checkLicenseExpirationDate function and simplified date handling in the findLatestExpirationDate function.
    • Updated logic for determining the latest expiration date to improve efficiency.
    • Reorganized tests to better reflect the new license expiration date handling.

@thorkellmani thorkellmani requested review from a team as code owners October 31, 2024 13:58
Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Walkthrough

The pull request introduces modifications to the MachineLicenseClient class and the machineLicenseMapper.ts file. Key changes include the addition of a date comparison utility using compareAsc from the date-fns library in machineLicenseClient.service.ts, enhancing the license validity check logic. In machineLicenseMapper.ts, the checkLicenseExpirationDate function is removed, and the date comparison logic is streamlined using a new helper function, compareDates, which simplifies the determination of the latest expiration date.

Changes

File Change Summary
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.service.ts Added import for compareAsc and updated checkLicenseValidityForPkPass to enhance expiration date checks.
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseMapper.ts Removed checkLicenseExpirationDate function; updated findLatestExpirationDate to use compareDates.
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.spec.ts Removed tests associated with checkLicenseExpirationDate; retained tests for findLatestExpirationDate.

Possibly related PRs

Suggested labels

automerge, high priority

Suggested reviewers

  • thordurhhh
  • rafnarnason

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.

@thorkellmani thorkellmani added the deploy-feature Deploys features to dev label Oct 31, 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: 2

🧹 Outside diff range and nitpick comments (4)
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseMapper.ts (3)

12-13: Add type safety and documentation to the compareDates helper.

The function logic is correct, but could benefit from additional type safety and documentation.

Consider applying these improvements:

+/**
+ * Compares two dates and returns the later one
+ * @param newDate - The date to compare
+ * @param latestDate - Optional reference date
+ * @returns The later date between the two
+ */
-const compareDates = (newDate: Date, latestDate?: Date) =>
+const compareDates = (newDate: Date | string, latestDate?: Date | string) => {
+  const newDateTime = new Date(newDate)
+  const latestDateTime = latestDate ? new Date(latestDate) : undefined
+  
+  if (isNaN(newDateTime.getTime())) {
+    throw new Error('Invalid newDate')
+  }
+  if (latestDateTime && isNaN(latestDateTime.getTime())) {
+    throw new Error('Invalid latestDate')
+  }
+  
+  return !latestDateTime || newDateTime > latestDateTime ? newDateTime : latestDateTime
+}

20-30: Enhance type safety and readability of findLatestExpirationDate.

The refactored implementation is cleaner and more maintainable.

Consider these improvements:

-export const findLatestExpirationDate = (license: VinnuvelaDto) => {
+export const findLatestExpirationDate = (license: VinnuvelaDto): string | null => {
   if (!license.vinnuvelaRettindi) {
     return null
   }

   let latestDate: Date | undefined
-  for (const right of license.vinnuvelaRettindi) {
+  license.vinnuvelaRettindi.forEach((right) => {
     if (right.stjorna) {
       latestDate = compareDates(new Date(right.stjorna), latestDate)
     }
     if (right.kenna) {
       latestDate = compareDates(new Date(right.kenna), latestDate)
     }
-  }
+  })

   return latestDate ? latestDate.toISOString() : null
 }

Line range hint 1-116: Add explicit return types to exported functions.

The code demonstrates good TypeScript practices and reusability. However, some exported functions would benefit from explicit return type annotations.

Add return types to these functions:

-export const parseRightsForPkpassInput = (
+export const parseRightsForPkpassInput = (
   rights?: Array<VinnuvelaRettindiDto>,
   locale?: Locale,
-) => {
+): string => {

-export const createPkPassDataInput = (
+export const createPkPassDataInput = (
   license: VinnuvelaDto,
   nationalId: string,
   locale?: Locale,
-) => {
+): Array<{ identifier: string; value: string }> | null => {
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.service.ts (1)

49-51: Add type safety for expiration date.

The expirationDate variable lacks type information, which could lead to runtime issues.

-    const expirationDate = licenseInfo
+    const expirationDate: string | null = licenseInfo
       ? findLatestExpirationDate(licenseInfo)
       : null
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 72d681b and b679c76.

📒 Files selected for processing (2)
  • libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.service.ts (2 hunks)
  • libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseMapper.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.service.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseMapper.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (1)
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.service.ts (1)

49-62: Verify the impact of updated license validation logic.

The changes to license validation logic might affect other parts of the codebase that rely on this validation.

✅ Verification successful

The search results show that the LicensePkPassAvailability enum is consistently used across multiple license client services (hunting, firearm, machine, ADR, driving, and disability) with the same pattern of returning Unknown, NotAvailable, or Available based on license validation. The changes in the machine license client follow this same pattern and maintain consistency with other implementations.

Let me verify the specific implementation pattern by searching for the actual validation logic:


License validation changes maintain consistent behavior

The changes to the license validation logic in machineLicenseClient.service.ts follow the established pattern across all license client services. The findLatestExpirationDate function is properly scoped to the machine license module and is used consistently within its service. The validation logic maintains the same LicensePkPassAvailability enum states (Unknown, NotAvailable, Available) as other license client implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of LicensePkPassAvailability and potential impacts

# Test 1: Find all usages of LicensePkPassAvailability enum
echo "Checking LicensePkPassAvailability usage:"
rg "LicensePkPassAvailability\." -A 3

# Test 2: Find all implementations of checkLicenseValidityForPkPass
echo -e "\nChecking checkLicenseValidityForPkPass implementations:"
ast-grep --pattern 'checkLicenseValidityForPkPass($_) { $$$ }'

Length of output: 11570


Script:

#!/bin/bash
# Search for license validation implementations
echo "Checking license validation patterns:"
ast-grep --pattern 'checkLicenseValidityForPkPass($_) {
  $$$
}'

# Search for findLatestExpirationDate usage
echo -e "\nChecking findLatestExpirationDate usage:"
rg "findLatestExpirationDate" -A 3

Length of output: 3293

Copy link
Contributor

@thoreyjona thoreyjona 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 too me, haven't tested yet though 😄 One comment to see if I'm understanding correctly.

Copy link

codecov bot commented Oct 31, 2024

Codecov Report

Attention: Patch coverage is 53.33333% with 7 lines in your changes missing coverage. Please review.

Project coverage is 36.53%. Comparing base (03b426a) to head (b0af565).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...ine-license-client/machineLicenseClient.service.ts 12.50% 7 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16679      +/-   ##
==========================================
- Coverage   36.54%   36.53%   -0.01%     
==========================================
  Files        6890     6890              
  Lines      143640   143638       -2     
  Branches    40926    40924       -2     
==========================================
- Hits        52488    52479       -9     
- Misses      91152    91159       +7     
Flag Coverage Δ
api 3.37% <ø> (ø)
clients-license-client 1.26% <46.66%> (-0.57%) ⬇️
judicial-system-backend 55.17% <ø> (ø)
license-api 42.62% <13.33%> (+0.07%) ⬆️

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

Files with missing lines Coverage Δ
...nts/machine-license-client/machineLicenseMapper.ts 39.13% <100.00%> (-8.15%) ⬇️
...ine-license-client/machineLicenseClient.service.ts 13.00% <12.50%> (+0.09%) ⬆️

... and 1 file 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 03b426a...b0af565. Read the comment docs.

Copy link
Contributor

github-actions bot commented Oct 31, 2024

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 31, 2024

Datadog Report

All test runs 5f5c0ae 🔗

3 Total Test Services: 0 Failed, 2 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.26%), 4 no change

Test Services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.38s 1 no change Link
api-domains-license-service 0 0 0 0 0 485.5ms 1 no change Link
license-api 0 0 0 80 0 23.66s 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • clients-license-client - jest 1.54% (-0.26%) - Details

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

🧹 Outside diff range and nitpick comments (1)
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.spec.ts (1)

10-10: Consider using a more reasonable test date.

The test uses a hardcoded date far in the future (2080). While this works, it's better to use a more reasonable date range to prevent the test from becoming outdated or misleading.

-const expectedDate = new Date('2080-01-01T00:00:00Z').toISOString()
+const expectedDate = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString() // One year from now
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 19c46cc and 3525f5d.

📒 Files selected for processing (1)
  • libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.spec.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."

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 (2)
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.spec.ts (2)

7-13: Improve test reliability and precision.

Two suggestions for improvement:

  1. Use toBe instead of toMatch for exact string comparison
  2. Consider using a more maintainable approach for test dates
-        expect(result).toMatch(expectedDate)
+        expect(result).toBe(expectedDate)

Consider using a relative date calculation instead of a hardcoded future date:

const futureDate = new Date()
futureDate.setFullYear(futureDate.getFullYear() + 1)
const expectedDate = futureDate.toISOString()

14-18: Remove unnecessary async keyword.

The test function doesn't contain any asynchronous operations, so the async keyword can be removed.

-      it('should return undefined if no license info', async () => {
+      it('should return undefined if no license info', () => {
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3525f5d and d590ec4.

📒 Files selected for processing (1)
  • libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.spec.ts (1)

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

  • Reusability of components and hooks across different NextJS apps.
  • TypeScript usage for defining props and exporting types.
  • Effective tree-shaking and bundling practices."
🔇 Additional comments (3)
libs/clients/license-client/src/lib/clients/machine-license-client/machineLicenseClient.spec.ts (3)

5-6: LGTM! Clear and descriptive test structure.

The describe blocks are well-organized and accurately reflect the test suite's purpose.


20-31: LGTM! Well-structured test for multiple dates.

The test effectively verifies the handling of multiple expiration dates with clear test data.


33-40: LGTM! Good error handling coverage.

The test properly verifies the handling of invalid date formats.

@thorkellmani thorkellmani added deploy-feature Deploys features to dev automerge Merge this PR as soon as all checks pass and removed deploy-feature Deploys features to dev labels Nov 6, 2024
@kodiakhq kodiakhq bot merged commit 7bbca02 into main Nov 6, 2024
43 checks passed
@kodiakhq kodiakhq bot deleted the fix/pkpass-status-machine-license branch November 6, 2024 14:55
robertaandersen pushed a commit that referenced this pull request Nov 11, 2024
* fix: init

* fix: type

* fix: date wrangling

* fix: tests

* fix: build

* fix: machine license client tests

* fix: remove invalid tests

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
jonnigs pushed a commit that referenced this pull request Nov 12, 2024
* fix: init

* fix: type

* fix: date wrangling

* fix: tests

* fix: build

* fix: machine license client tests

* fix: remove invalid tests

---------

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass deploy-feature Deploys features to dev
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants