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(assets): bulk mileage fixes #16253

Merged
merged 3 commits into from
Oct 3, 2024
Merged

fix(assets): bulk mileage fixes #16253

merged 3 commits into from
Oct 3, 2024

Conversation

thorkellmani
Copy link
Member

@thorkellmani thorkellmani commented Oct 3, 2024

...

Attach a link to issue if relevant

What

Specify what you're trying to achieve

Why

Specify why you need to achieve this

Screenshots / Gifs

Attach Screenshots / Gifs to help reviewers understand the scope of the pull request

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 logging capabilities for mileage updates.
    • Simplified response handling for mileage reading submissions.
  • Bug Fixes

    • Improved input validation for mileage entries to prevent runtime errors.
    • Corrected success state management during mileage submissions.
  • Documentation

    • Updated API response structure for mileage reading submissions to reflect resource creation.
  • Style

    • Minor adjustments to JSX formatting for better maintainability.

@thorkellmani thorkellmani requested a review from a team as a code owner October 3, 2024 10:48
Copy link
Contributor

coderabbitai bot commented Oct 3, 2024

Walkthrough

The pull request introduces several modifications across multiple files related to vehicle mileage management. Key changes include the addition of a logger dependency in the VehiclesMileageResolver class, updates to the response handling in the putVehicleMileageReading method, and a change in the return type of the putMileageReading method in the VehiclesService class to return a single object instead of an array. Additionally, updates to the OpenAPI specification for the PUT / endpoint reflect a change in response status and structure. Other components also see refinements in state management and validation logic.

Changes

File Change Summary
libs/api/domains/vehicles/src/lib/resolvers/mileage.resolver.ts Updated VehiclesMileageResolver constructor to include a logger dependency. Modified putVehicleMileageReading method to check for falsy response and return the entire response instead of the first element.
libs/api/domains/vehicles/src/lib/services/vehicles.service.ts Changed return type of putMileageReading method from `Promise<Array
libs/clients/vehicles-mileage/src/clientConfig.json Updated OpenAPI specification: changed response status code for PUT / from 200 to 201 and modified response schema to return a single MileageReadingDto object instead of an array.
libs/service-portal/assets/src/screens/VehicleBulkMileage/VehicleBulkMileageRow.tsx Modified state management for success handling in mileage submissions, ensuring setPostSuccess is set to true upon successful completion of both mutations. Error handling logic remains unchanged.
libs/service-portal/assets/src/screens/VehicleMileage/VehicleMileage.tsx Updated mileage input validation logic to safely access the latest registered mileage and refined rendering conditions based on error presence and registration requirements. Minor formatting adjustments made.
libs/service-portal/core/src/components/NestedTable/NestedFullTable.tsx Changed condition for checking if data array has elements from data.length to !!data.length for clarity. Overall rendering behavior remains unchanged.

Possibly related PRs

Suggested labels

automerge


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: 0

🧹 Outside diff range and nitpick comments (7)
libs/service-portal/core/src/components/NestedTable/NestedFullTable.tsx (2)

Line range hint 8-13: Enhance type safety for better reusability

To improve type safety and make this component more reusable across different NextJS apps, consider using a more specific type for the data prop. Instead of Array<string[]>, you could define a generic type parameter. This would allow consumers of the component to specify the exact shape of their data.

Here's a suggestion:

interface Props<T extends string[]> {
  headerArray: string[]
  data: T[]
  loading?: boolean
  emptyMessage?: string
}

export const NestedFullTable = <T extends string[]>({
  headerArray,
  data,
  loading,
  emptyMessage,
}: Props<T>) => {
  // ... rest of the component
}

This change would make the component more flexible and type-safe when used in different contexts.


Line range hint 22-69: Add null check for data prop

To improve the robustness of the component, consider adding a null check for the data prop. This will prevent potential runtime errors if data is undefined.

Here's a suggestion:

{!loading && data && !!data.length && (
  <T.Table>
    {/* ... existing table code ... */}
  </T.Table>
)}
{(loading || !data || !data.length) && (
  <EmptyTable
    loading={loading}
    message={emptyMessage ?? 'Ekkert fannst'}
  />
)}

This change ensures that the component handles cases where data might be undefined, further improving its reusability across different contexts.

libs/api/domains/vehicles/src/lib/resolvers/mileage.resolver.ts (1)

45-48: LGTM: Constructor updated with logger injection.

The constructor has been correctly updated to inject a logger, which enhances the class's logging capabilities. The use of @Inject(LOGGER_PROVIDER) and TypeScript typing for the logger is correct and follows NestJS best practices.

Consider using a more specific logger name, such as vehiclesMileageLogger, to improve code readability and maintain consistency across the codebase.

libs/service-portal/assets/src/screens/VehicleMileage/VehicleMileage.tsx (2)

252-253: LGTM! Consider adding a type assertion for clarity.

The use of optional chaining and a fallback value improves the robustness of the code. Great job!

For improved clarity and type safety, consider adding a type assertion:

const latestRegistration = (detailArray?.[0]?.mileageNumber ?? 0) as number;

This explicitly indicates that latestRegistration is always a number, which may help prevent type-related issues in the future.


Line range hint 1-424: Enhance type definitions and exports for better adherence to coding guidelines.

The file generally follows the coding guidelines for libs/**/* files. However, consider the following improvements:

  1. Define and export interface for component props to enhance reusability:

    export interface VehicleMileageProps {
      // Add any props here if needed
    }
    
    const VehicleMileage: React.FC<VehicleMileageProps> = () => {
      // ... component implementation
    }
  2. Export types used in the component to improve reusability across different NextJS apps:

    export interface FormData {
      odometerStatus: number
    }
  3. Consider extracting reusable logic (e.g., mileage validation) into a custom hook for better modularity and reusability.

These changes will further align the component with the coding guidelines, enhancing its reusability and type safety across different NextJS apps.

libs/api/domains/vehicles/src/lib/services/vehicles.service.ts (1)

Line range hint 446-461: LGTM! Consider enhancing error handling.

The changes to the putMileageReading method look good. The return type now correctly reflects that a single MileageReadingDto is being updated, which aligns better with the method's purpose. The simplified implementation is more concise and easier to understand.

Consider adding a try-catch block to handle potential errors from the rootPut call:

try {
  return this.getMileageWithAuth(auth).rootPut({
    putMileageReadingModel: input,
  });
} catch (error) {
  this.logger.error('Error updating mileage reading', {
    category: LOG_CATEGORY,
    error,
  });
  throw error;
}

This would provide better error logging and maintain consistency with error handling patterns used elsewhere in the service.

libs/clients/vehicles-mileage/src/clientConfig.json (1)

Line range hint 1-1005: Summary of changes and potential impact

The modifications to the OpenAPI specification for the SGS Rest API, specifically in the PUT / endpoint response, improve the API's consistency and adherence to RESTful best practices. However, these changes may have implications for existing client applications:

  1. Clients expecting a 200 status code will need to be updated to handle 201.
  2. Any code processing the response as an array will need to be modified to handle a single object.

To ensure a smooth transition:

  1. Update all client applications consuming this API to accommodate these changes.
  2. Consider versioning the API or providing a deprecation period if immediate updates to all clients are not feasible.
  3. Update any documentation or API guides to reflect these changes.

Consider implementing API versioning to allow for smoother transitions in future API changes. This could involve including version numbers in the URL path or using custom headers to specify the API version.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e8844cb and 3101fba.

📒 Files selected for processing (6)
  • libs/api/domains/vehicles/src/lib/resolvers/mileage.resolver.ts (3 hunks)
  • libs/api/domains/vehicles/src/lib/services/vehicles.service.ts (2 hunks)
  • libs/clients/vehicles-mileage/src/clientConfig.json (1 hunks)
  • libs/service-portal/assets/src/screens/VehicleBulkMileage/VehicleBulkMileageRow.tsx (2 hunks)
  • libs/service-portal/assets/src/screens/VehicleMileage/VehicleMileage.tsx (1 hunks)
  • libs/service-portal/core/src/components/NestedTable/NestedFullTable.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
libs/api/domains/vehicles/src/lib/resolvers/mileage.resolver.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/api/domains/vehicles/src/lib/services/vehicles.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/vehicles-mileage/src/clientConfig.json (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/service-portal/assets/src/screens/VehicleBulkMileage/VehicleBulkMileageRow.tsx (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/service-portal/assets/src/screens/VehicleMileage/VehicleMileage.tsx (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/service-portal/core/src/components/NestedTable/NestedFullTable.tsx (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 (7)
libs/service-portal/core/src/components/NestedTable/NestedFullTable.tsx (1)

22-22: Approved: Improved boolean condition clarity

The change from data.length to !!data.length explicitly converts the length to a boolean value. While this doesn't alter the behavior, it improves code readability by making the intent clearer. This is a good practice in TypeScript/JavaScript.

libs/api/domains/vehicles/src/lib/resolvers/mileage.resolver.ts (2)

10-10: LGTM: Import statements are well-structured and follow best practices.

The new import statements for Inject, LOGGER_PROVIDER, and Logger type are correctly added and follow TypeScript best practices. These specific imports support effective tree-shaking.

Also applies to: 37-37


95-97: Simplified condition approved, but clarification needed on return statement change.

The simplification of the condition check improves code readability. However, the change in the return statement from res[0] to res might affect the method's behavior.

Could you please clarify the rationale behind changing mileageDetailConstructor(res[0]) to mileageDetailConstructor(res)? This change might impact the output of the mutation.

To verify the impact, let's check the implementation of mileageDetailConstructor:

Also applies to: 99-99

libs/service-portal/assets/src/screens/VehicleBulkMileage/VehicleBulkMileageRow.tsx (3)

50-50: LGTM: Improved error handling consistency

This change ensures that the postSuccess state is reset to false when an error occurs during the put action, maintaining consistency with the error handling in the post action. This improvement enhances the overall state management of the component.


62-66: LGTM: Fixed success state management

These changes improve the state management for the post action:

  1. Line 62: Adding setPostSuccess(false) in the onError callback ensures consistent error handling with the put action.
  2. Line 66: Changing setPostSuccess(false) to setPostSuccess(true) in the onCompleted callback fixes a critical logical error. This ensures that the success state accurately reflects the successful completion of the post action.

These improvements will lead to more accurate UI feedback and better overall component behavior.


Line range hint 1-324: Overall assessment: Improved state management

The changes in this file focus on enhancing the state management for success and error handling in the VehicleBulkMileageRow component. These improvements lead to more accurate UI feedback and better overall component behavior.

The modifications align well with the coding guidelines:

  1. Reusability: The component's structure remains unchanged, maintaining its potential for reuse across different NextJS apps.
  2. TypeScript usage: The changes don't affect the existing TypeScript implementations, preserving type safety.
  3. Effective tree-shaking and bundling: No changes were made that would negatively impact bundling practices.

These refinements contribute to a more robust and reliable component without introducing any new issues or compromising existing functionality.

libs/clients/vehicles-mileage/src/clientConfig.json (1)

246-252: Approve the changes to the PUT / endpoint response.

The modifications to the PUT / endpoint response are appropriate and align with RESTful API best practices:

  1. Changing the status code from 200 to 201 is correct for a resource creation operation.
  2. Updating the response schema from an array to a single object is more consistent with typical PUT operation responses.

These changes improve the API's consistency and adherence to standards.

To ensure these changes don't introduce breaking changes for existing clients, please run the following verification script:

This script will help identify any client code that might need to be updated to handle the new response format.

@thorkellmani thorkellmani added the automerge Merge this PR as soon as all checks pass label Oct 3, 2024
@thorkellmani thorkellmani added the deploy-feature Deploys features to dev label Oct 3, 2024
Copy link

codecov bot commented Oct 3, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 36.92%. Comparing base (7eb0c62) to head (810385e).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main   #16253   +/-   ##
=======================================
  Coverage   36.92%   36.92%           
=======================================
  Files        6781     6781           
  Lines      140009   140009           
  Branches    39810    39810           
=======================================
  Hits        51703    51703           
  Misses      88306    88306           
Flag Coverage Δ
api 3.37% <ø> (ø)
application-system-api 41.63% <ø> (ø)
application-template-api-modules 24.38% <ø> (-0.02%) ⬇️

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


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 7eb0c62...810385e. Read the comment docs.

@datadog-island-is
Copy link

Datadog Report

All test runs 6c00652 🔗

5 Total Test Services: 0 Failed, 4 Passed
🔻 Test Sessions change in coverage: 1 decreased (-0.01%), 28 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.77s 1 no change Link
application-system-api 0 0 0 120 2 3m 18.15s 1 no change Link
application-template-api-modules 0 0 0 135 0 1m 58.57s 1 decreased (-0.01%) Link
service-portal-core 0 0 0 5 0 1.91s N/A Link
service-portal-health 0 0 0 0 0 639.17ms 1 no change Link

🔻 Code Coverage Decreases vs Default Branch (1)

  • application-template-api-modules - jest 26.06% (-0.01%) - Details

@kodiakhq kodiakhq bot merged commit 4706157 into main Oct 3, 2024
72 checks passed
@kodiakhq kodiakhq bot deleted the feat/bulk-mileage-fixes branch October 3, 2024 11:22
@coderabbitai coderabbitai bot mentioned this pull request Dec 19, 2024
6 tasks
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.

2 participants