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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

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.

@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
  • albinagu

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.63%. Comparing base (5d1f145) to head (3525f5d).
Report is 6 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.67%   36.63%   -0.04%     
==========================================
  Files        6858     6872      +14     
  Lines      142787   143113     +326     
  Branches    40703    40788      +85     
==========================================
+ Hits        52364    52436      +72     
- Misses      90423    90677     +254     
Flag Coverage Δ
api 3.37% <ø> (ø)
clients-license-client 1.26% <46.66%> (-0.57%) ⬇️
license-api 42.75% <13.33%> (+0.29%) ⬆️

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 29 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 72d681b...3525f5d. 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 87de3d9 🔗

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.65s 1 no change Link
api-domains-license-service 0 0 0 0 0 542.58ms 1 no change Link
license-api 0 0 0 80 0 24.93s 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."

Comment on lines +6 to +18
describe('get latest license qualification expiration date', () => {
it('should return the latest license right date', async () => {
const result = mapper.findLatestExpirationDate(ValidMachineLicense)

const expectedDate = new Date('2080-01-01T00:00:00Z').toISOString()
const expectedDate = new Date('2080-01-01T00:00:00Z').toISOString()

expect(result).toMatch(expectedDate)
})
it('should return undefined if no license info', async () => {
const result = mapper.findLatestExpirationDate({})
expect(result).toMatch(expectedDate)
})
it('should return undefined if no license info', async () => {
const result = mapper.findLatestExpirationDate({})

expect(result).toBeNull
expect(result).toBeNull
})
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage with additional test cases.

The current test suite could benefit from additional test cases to ensure robust functionality:

  1. Test with multiple dates to verify the latest date is correctly identified
  2. Test with invalid date formats
  3. Test with empty date fields

Here's a suggested addition to improve coverage:

it('should handle multiple dates and return the latest', () => {
  const licenseWithMultipleDates = {
    ...ValidMachineLicense,
    qualifications: [
      { expiryDate: '2023-01-01T00:00:00Z' },
      { expiryDate: '2023-12-31T00:00:00Z' },
      { expiryDate: '2023-06-01T00:00:00Z' }
    ]
  }
  const result = mapper.findLatestExpirationDate(licenseWithMultipleDates)
  expect(result).toBe('2023-12-31T00:00:00Z')
})

it('should handle invalid date formats gracefully', () => {
  const licenseWithInvalidDate = {
    ...ValidMachineLicense,
    qualifications: [
      { expiryDate: 'invalid-date' }
    ]
  }
  const result = mapper.findLatestExpirationDate(licenseWithInvalidDate)
  expect(result).toBeNull()
})

@@ -1,34 +1,21 @@
import * as mapper from './machineLicenseMapper'
import ExpiredMachineLicense from '../__mock_data/expiredMachineLicense.json'
import ValidMachineLicense from '../__mock_data/validMachineLicense.json'

describe('license-service/client/machine-license', () => {
describe('check if expired', () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update the describe block description.

The describe block "check if expired" is misleading as the tests now focus on finding the latest expiration date rather than checking if a license is expired.

-describe('check if expired', () => {
+describe('license expiration date handling', () => {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
describe('check if expired', () => {
describe('license expiration date handling', () => {


expect(result).toBeNull
expect(result).toBeNull
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the assertion syntax error.

The assertion is missing parentheses which makes it ineffective. The test is currently checking if the toBeNull matcher exists rather than if the value is null.

-expect(result).toBeNull
+expect(result).toBeNull()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
expect(result).toBeNull
expect(result).toBeNull()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deploy-feature Deploys features to dev
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants