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(vnpay): 🔧 refactor for readable and add tests #19

Merged
merged 19 commits into from
Jul 20, 2024

Conversation

lehuygiang28
Copy link
Owner

@lehuygiang28 lehuygiang28 commented Jul 20, 2024

Summary by Sourcery

This pull request refactors the VNPay class for better readability and maintainability, introduces new utility functions for date handling and secure hash calculation, and updates the logging functionality. It also includes updates to tests and configuration files.

  • Enhancements:
    • Refactored VNPay class to improve readability and maintainability by extracting utility functions for URL creation and secure hash calculation.
    • Enhanced date handling by introducing a new utility function getDateInGMT7 and updating parseDate to support different time zones.
    • Improved logging functionality by allowing the consoleLogger to specify the console method to use.
  • Tests:
    • Added tests for the new utility functions in payment.util.ts.
    • Updated existing tests to use the new getDateInGMT7 function for consistent date handling.
  • Chores:
    • Updated .coderabbit.yaml configuration to include tone instructions for feedback.

Summary by CodeRabbit

  • New Features

    • Introduced a new configuration option to guide the tone of feedback for improved communication.
    • Added utility functions for payment processing, including URL construction and secure hash calculations.
    • Enhanced date handling functions for better timezone support.
  • Bug Fixes

    • Improved date formatting accuracy for payment URLs by standardizing to GMT+7.
  • Tests

    • Added extensive unit tests for new utility functions and payment processing logic to ensure reliability and correctness.

@lehuygiang28 lehuygiang28 self-assigned this Jul 20, 2024
Copy link

vercel bot commented Jul 20, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
vnpay ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 20, 2024 8:43pm

Copy link

sourcery-ai bot commented Jul 20, 2024

Reviewer's Guide by Sourcery

This pull request refactors the VNPay module for improved readability and maintainability. Key changes include modularizing the payment URL creation and secure hash calculation into separate utility functions, enhancing date handling functions, and updating tests accordingly. Additionally, the jest configuration was updated to set the timezone to UTC and enforce a minimum coverage threshold. The console logger was also enhanced to support different console methods.

File-Level Changes

Files Changes
src/vnpay.ts
src/utils/payment.util.ts
Refactored payment URL creation and secure hash calculation into separate utility functions for better modularity and readability.
src/utils/common.ts
test/build-payment-url.test.ts
Enhanced date handling functions and updated tests to use the new date utility functions.

Tips
  • Trigger a new Sourcery review by commenting @sourcery-ai review on the pull request.
  • Continue your discussion with Sourcery by replying directly to review comments.
  • You can change your review settings at any time by accessing your dashboard:
    • Enable or disable the Sourcery-generated pull request summary or reviewer's guide;
    • Change the review language;
  • You can always contact us if you have any questions or feedback.

Copy link

coderabbitai bot commented Jul 20, 2024

Walkthrough

The recent changes enhance the configuration and functionality of the project, introducing improvements in feedback tone guidance, file ignoring during linting and publishing processes, and significant updates to payment handling utilities. Notable additions include a clear professional tone in feedback, new utility functions for payment processing, and comprehensive testing for these functionalities, all aimed at improving code quality and maintainability.

Changes

File(s) Change Summary
.coderabbit.yaml Added tone_instructions for clearer, more professional feedback.
.eslintignore, .npmignore Added coverage/ directory to ignore lists, optimizing linting and package size.
.gitignore Changed .env from ignored to tracked; added coverage/ to ignore list.
jest.config.ts Set timezone to UTC and added coverageThreshold for minimum test coverage of 80%.
package.json Introduced "test:cov" script to run tests with coverage reporting enabled.
src/utils/common.ts Enhanced getDateInGMT7 and parseDate functions for better timezone support.
src/utils/index.ts Added export for payment.util functions, improving modularity.
src/utils/logger.ts Updated consoleLogger to accept a log method parameter, enhancing flexibility in logging output.
src/utils/payment.util.ts Introduced utilities for payment URL construction and secure hash calculations for transaction integrity.
src/vnpay.ts Refactored payment processing logic to utilize new utility functions and improved date handling.
test/... (various) Added comprehensive tests for date handling, logging utilities, and payment functions, ensuring correctness and reliability across functionalities.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PaymentProcessor
    participant PaymentUtil
    participant Logger

    User->>PaymentProcessor: Initiate Payment
    PaymentProcessor->>PaymentUtil: Build Payment URL
    PaymentUtil-->>PaymentProcessor: Return Payment URL
    PaymentProcessor->>Logger: Log Payment Initiation
    Logger-->>PaymentProcessor: Acknowledge Log
    PaymentProcessor->>User: Confirm Payment Processing
Loading

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @lehuygiang28 - I've reviewed your changes and they look great!

Here's what I looked at during the review
  • 🟡 General issues: 4 issues found
  • 🟢 Security: all looks good
  • 🟡 Testing: 1 issue found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment to tell me if it was helpful.

/**
* Multiply by 100 to follow VNPay standard, see docs for more detail
*/
vnp_Amount: data.vnp_Amount * 100,
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): Potential issue with undefined data.vnp_Amount.

If data.vnp_Amount is undefined, this line will result in NaN. Consider adding a check or default value.

src/vnpay.ts Show resolved Hide resolved

redirectUrl.searchParams.append(key, value.toString());
});
const redirectUrl = createPaymentUrl(this.globalDefaultConfig, dataToBuild);
Copy link

Choose a reason for hiding this comment

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

issue: Potential issue with createPaymentUrl function.

Ensure that createPaymentUrl handles all edge cases, such as missing or malformed URLs, to avoid runtime errors.

src/utils/common.ts Show resolved Hide resolved
@@ -147,7 +147,7 @@ describe('buildPaymentUrl', () => {
...baseInput,
};
delete input.vnp_CreateDate;
const currentTime = dateFormat(new Date());
const currentTime = dateFormat(getDateInGMT7());
Copy link

Choose a reason for hiding this comment

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

suggestion (testing): Add test for missing vnp_CreateDate edge case

Consider adding a test case to verify the behavior when vnp_CreateDate is missing. This will ensure that the getDateInGMT7 function is correctly setting the date.

Suggested change
const currentTime = dateFormat(getDateInGMT7());
test('should handle missing vnp_CreateDate by using current time in GMT+7', () => {
const input = { /* your input object without vnp_CreateDate */ };
const currentTime = dateFormat(getDateInGMT7());
const result = vnpay.buildPaymentUrl(input);
expect(result).toContain(currentTime);
});

@lehuygiang28
Copy link
Owner Author

@coderabbitai review

Copy link

coderabbitai bot commented Jul 20, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

@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 comments (1)
src/utils/common.ts (1)

Line range hint 45-70: Remove the redundant case clause.

The case 'local': clause is redundant because the default clause handles it.

-        case 'local':
Tools
Biome

[error] 68-69: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)


[error] 55-55: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


[error] 56-56: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between 4c1c781 and e22058f.

Files selected for processing (17)
  • .coderabbit.yaml (1 hunks)
  • .eslintignore (1 hunks)
  • .gitignore (1 hunks)
  • .npmignore (1 hunks)
  • .prettierignore (1 hunks)
  • jest.config.ts (1 hunks)
  • package.json (1 hunks)
  • src/utils/common.ts (3 hunks)
  • src/utils/index.ts (1 hunks)
  • src/utils/logger.ts (2 hunks)
  • src/utils/payment.util.ts (1 hunks)
  • src/vnpay.ts (5 hunks)
  • test/build-payment-url.test.ts (2 hunks)
  • test/utils/common.test.ts (1 hunks)
  • test/utils/logger.test.ts (1 hunks)
  • test/utils/payment-util.test.ts (1 hunks)
  • test/verify-return-url.test.ts (1 hunks)
Additional context used
Path-based instructions (11)
src/utils/index.ts (1)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.

jest.config.ts (1)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.

src/utils/logger.ts (1)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.

src/utils/payment.util.ts (1)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.

test/utils/logger.test.ts (2)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.


Pattern test/**/*: Review the test files to ensure they cover all the relevant use cases and edge cases of the codebase. Check for proper test coverage, assertions, and error handling. Ensure that the tests are well-organized, easy to read, and provide meaningful feedback. Highlight any missing or redundant tests and suggest improvements to enhance the overall quality of the test suite.

test/utils/payment-util.test.ts (2)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.


Pattern test/**/*: Review the test files to ensure they cover all the relevant use cases and edge cases of the codebase. Check for proper test coverage, assertions, and error handling. Ensure that the tests are well-organized, easy to read, and provide meaningful feedback. Highlight any missing or redundant tests and suggest improvements to enhance the overall quality of the test suite.

src/utils/common.ts (1)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.

test/utils/common.test.ts (2)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.


Pattern test/**/*: Review the test files to ensure they cover all the relevant use cases and edge cases of the codebase. Check for proper test coverage, assertions, and error handling. Ensure that the tests are well-organized, easy to read, and provide meaningful feedback. Highlight any missing or redundant tests and suggest improvements to enhance the overall quality of the test suite.

test/verify-return-url.test.ts (2)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.


Pattern test/**/*: Review the test files to ensure they cover all the relevant use cases and edge cases of the codebase. Check for proper test coverage, assertions, and error handling. Ensure that the tests are well-organized, easy to read, and provide meaningful feedback. Highlight any missing or redundant tests and suggest improvements to enhance the overall quality of the test suite.

test/build-payment-url.test.ts (2)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.


Pattern test/**/*: Review the test files to ensure they cover all the relevant use cases and edge cases of the codebase. Check for proper test coverage, assertions, and error handling. Ensure that the tests are well-organized, easy to read, and provide meaningful feedback. Highlight any missing or redundant tests and suggest improvements to enhance the overall quality of the test suite.

src/vnpay.ts (1)

Pattern **/*.ts: Review the TypeScript code of the NPM package to ensure it adheres to the principles of awesome and clean code. This includes proper use of functions, classes, modules. Also, ensure the code follows best practices for package development, such as clear and concise documentation, proper error handling, and efficient data structures and algorithms. The code should also conform to the ESLint rules configured in the codebase. Highlight any deviations and suggest appropriate corrections. Using design patterns that promote code reusability and readability is encouraged.

Biome
test/utils/logger.test.ts

[error] 38-38: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 52-52: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


[error] 64-64: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

src/utils/common.ts

[error] 68-69: Useless case clause.

because the default clause is present:

Unsafe fix: Remove the useless case.

(lint/complexity/noUselessSwitchCase)

Additional comments not posted (53)
.gitignore (2)

4-4: Verify the inclusion of the .env file.

Including the .env file in version control can expose sensitive information. Ensure that this change is intentional and that the .env file does not contain sensitive data.


5-5: Good practice: Ignoring the coverage/ directory.

Adding the coverage/ directory to .gitignore is a good practice to avoid committing generated test coverage reports.

src/utils/index.ts (1)

3-3: LGTM!

Adding the export for payment.util enhances modularity and usability.

.npmignore (1)

6-6: Good practice: Ignoring the coverage/ directory.

Adding the coverage/ directory to .npmignore is a good practice to avoid including generated test coverage reports in the published package.

.prettierignore (1)

4-4: LGTM! Excluding coverage/ from Prettier checks is a good practice.

This change ensures that generated coverage reports are not unnecessarily formatted by Prettier.

.eslintignore (1)

4-4: LGTM! Excluding coverage/ from ESLint checks is a good practice.

This change ensures that generated coverage reports are not unnecessarily linted by ESLint.

jest.config.ts (2)

1-1: Setting the timezone to 'UTC' for consistent testing.

This change ensures that all tests run in the 'UTC' timezone, providing consistent date and time handling across tests.


6-10: Enforcing a minimum coverage threshold of 80%.

This change improves the reliability and maintainability of the codebase by ensuring that at least 80% of the lines of code are tested.

src/utils/logger.ts (2)

1-1: LGTM! Node.js-specific import for fs module.

The change aligns with modern JavaScript practices.


17-20: LGTM! Enhanced flexibility in consoleLogger function.

The additional symbol parameter allows specifying the console method, improving flexibility and ensuring type safety.

package.json (1)

19-19: LGTM! Added Jest coverage reporting script.

The new script command "test:cov": "jest --coverage" improves the testing workflow by providing an easy way to check code coverage.

src/utils/payment.util.ts (4)

6-18: LGTM! Efficiently builds URL search parameters.

The function sorts entries, skips empty values, and sets search parameters correctly.


20-34: LGTM! Creates payment URL efficiently.

The function resolves the URL string, builds search parameters, and sets them correctly.


36-43: LGTM! Calculates secure hash efficiently.

The function uses the hash utility to calculate the hash correctly.


45-53: LGTM! Verifies secure hash efficiently.

The function uses the calculateSecureHash utility to calculate the hash and compares it correctly.

.coderabbit.yaml (1)

4-4: Approved: Addition of tone instructions.

The addition of tone_instructions enhances the configuration by providing clear guidelines for feedback tone.

test/utils/logger.test.ts (6)

11-13: Approved: Test case for ignore logger.

The test case correctly verifies that ignoreLogger returns undefined.


15-20: Approved: Test case for logging data to console.

The test case correctly verifies that consoleLogger logs data to the console using jest.spyOn.


22-27: Approved: Test case for logging data to console with specific symbol.

The test case correctly verifies that consoleLogger logs data to the console with a specific symbol using jest.spyOn.


29-41: Approved with suggestion: Test case for logging data to file.

The test case correctly verifies that fileLogger logs data to a file. However, consider using template literals for string concatenation.

-  expect(appendFileMock).toHaveBeenCalledWith(
-      filePath,
-      JSON.stringify(data) + '\n',
-      expect.any(Function),
-  );
+  expect(appendFileMock).toHaveBeenCalledWith(
+      filePath,
+      `${JSON.stringify(data)}\n`,
+      expect.any(Function),
+  );
Tools
Biome

[error] 38-38: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


43-54: Approved with suggestion: Test case for handling file write error.

The test case correctly verifies that fileLogger handles file write errors with a callback. However, consider using template literals for string concatenation.

-  expect(appendFileMock).toHaveBeenCalledWith(filePath, data + '\n', expect.any(Function));
+  expect(appendFileMock).toHaveBeenCalledWith(filePath, `${data}\n`, expect.any(Function));
Tools
Biome

[error] 52-52: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)


56-65: Approved with suggestion: Test case for handling file write error without callback.

The test case correctly verifies that fileLogger handles file write errors without a callback. However, consider using template literals for string concatenation.

-  expect(() => fileLogger(data, filePath)).toThrowError(error);
-  expect(appendFileMock).toHaveBeenCalledWith(filePath, data + '\n', expect.any(Function));
+  expect(() => fileLogger(data, filePath)).toThrowError(error);
+  expect(appendFileMock).toHaveBeenCalledWith(filePath, `${data}\n`, expect.any(Function));
Tools
Biome

[error] 64-64: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

test/utils/payment-util.test.ts (6)

12-22: Approved: Test case for building search params from data.

The test case correctly verifies that buildPaymentUrlSearchParams builds search parameters from data.


23-31: Approved: Test case for skipping empty value.

The test case correctly verifies that buildPaymentUrlSearchParams skips empty values.


35-49: Approved: Test case for creating payment URL from config and data.

The test case correctly verifies that createPaymentUrl creates a payment URL from config and data.


51-62: Approved: Test case for creating a default payment URL.

The test case correctly verifies that createPaymentUrl creates a default payment URL.


65-73: Approved: Test case for calculating secure hash from data.

The test case correctly verifies that calculateSecureHash calculates the secure hash from data.


77-86: Approved: Test case for verifying secure hash.

The test case correctly verifies that verifySecureHash verifies the secure hash.

src/utils/common.ts (1)

6-9: LGTM!

The changes to getDateInGMT7 improve its flexibility by allowing an optional date parameter. The implementation using moment-timezone is correct.

test/utils/common.test.ts (8)

20-25: LGTM!

The test case correctly verifies the functionality of getDateInGMT7.


28-33: LGTM!

The test case correctly verifies the functionality of dateFormat.


36-47: LGTM!

The test cases correctly verify the functionality of parseDate.


50-59: LGTM!

The test cases correctly verify the functionality of isValidVnpayDateFormat.


62-73: LGTM!

The test cases correctly verify the functionality of generateRandomString.


76-94: LGTM!

The test cases correctly verify the functionality of getResponseByStatusCode.


97-114: LGTM!

The test case correctly verifies the functionality of resolveUrlString.


117-126: LGTM!

The test case correctly verifies the functionality of hash.

test/verify-return-url.test.ts (9)

39-72: LGTM!

The test case correctly verifies the functionality of verifyReturnUrl with valid input.


74-94: LGTM!

The parameterized test cases correctly verify the functionality of verifyReturnUrl with different amounts.


96-106: LGTM!

The test case correctly verifies the functionality of verifyReturnUrl for a success result.


109-127: LGTM!

The test case correctly verifies the functionality of verifyReturnUrl for a failed result.


130-147: LGTM!

The test case correctly verifies the functionality of verifyReturnUrl for a failed result with an invalid secure hash.


149-152: LGTM!

The test case correctly verifies the functionality of verifyReturnUrl for an invalid amount error.


154-163: LGTM!

The test case correctly verifies the functionality of verifyReturnUrl for amount conversion.


165-186: LGTM!

The test case correctly verifies the functionality of verifyReturnUrl for logging to the console.


188-211: LGTM!

The test case correctly verifies the functionality of verifyReturnUrl for logging to the console with secure hash.

test/build-payment-url.test.ts (1)

4-4: LGTM! Ensure consistent usage of getDateInGMT7.

The import statement has been updated to include getDateInGMT7. This change is approved.

Ensure that all occurrences of date handling in the test suite use this function for consistency.

src/vnpay.ts (6)

Line range hint 474-474:
LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to refund match the new logic.

Verification successful

Function usage verified successfully.

The refund function calls in the codebase match the new logic as expected. No issues were found.

  • example/index.ts: The refund function is called with the correct parameters.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `refund` match the new logic.

# Test: Search for the function usage. Expect: Only occurrences of the new logic.
rg --type typescript -A 5 $'refund'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify all function calls to `refund` match the new logic.

# Test: Search for the function usage. Expect: Only occurrences of the new logic.
rg --type ts -A 5 $'refund'

Length of output: 6452


16-16: LGTM! Ensure consistent usage of getDateInGMT7.

The import statement has been updated to include getDateInGMT7. This change is approved.

Ensure that all occurrences of date handling in the codebase use this function for consistency.

Verification successful

Consistent Usage of getDateInGMT7 Verified

The function getDateInGMT7 is consistently used across the codebase for date handling in GMT+7. This includes its usage in the main implementation as well as in test files.

  • Occurrences:
    • src/vnpay.ts
    • src/utils/common.ts
    • test/build-payment-url.test.ts
    • test/utils/common.test.ts

This ensures that date handling is standardized across the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all occurrences of date handling use `getDateInGMT7`.

# Test: Search for the function usage. Expect: Only occurrences of `getDateInGMT7`.
rg --type typescript -A 5 $'getDateInGMT7'

Length of output: 76


Script:

#!/bin/bash
# Description: Verify all occurrences of date handling use `getDateInGMT7`.

# Test: Search for the function usage. Expect: Only occurrences of `getDateInGMT7`.
rg --type ts -A 5 'getDateInGMT7'

Length of output: 2747


246-262: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to verifyReturnUrl match the new logic.


Line range hint 354-354:
LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to queryDr match the new logic.

Verification successful

Function queryDr usage verification:

The function queryDr is used correctly in the following files:

  • src/vnpay.ts: Method definition and internal usage.
  • example/index.ts: External function call.

The usage in example/index.ts aligns with the new logic defined in src/vnpay.ts.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `queryDr` match the new logic.

# Test: Search for the function usage. Expect: Only occurrences of the new logic.
rg --type typescript -A 5 $'queryDr'

Length of output: 70


Script:

#!/bin/bash
# Description: Verify all function calls to `queryDr` match the new logic.

# Test: Search for the function usage. Expect: Only occurrences of the new logic.
rg --type ts -A 5 $'queryDr'

Length of output: 1200


194-198: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to buildPaymentUrl match the new logic.

Verification successful

Function usage verified

The function calls to buildPaymentUrl have been verified, and they match the new logic of multiplying vnp_Amount by 100.

  • The tests in test/build-payment-url.test.ts confirm the correct implementation.
  • Example usages in example/index.ts and example/express.ts also align with the new logic.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `buildPaymentUrl` match the new logic.

# Test: Search for the function usage. Expect: Only occurrences of the new logic.
rg --type typescript -A 5 $'buildPaymentUrl'

Length of output: 78


Script:

#!/bin/bash
# Description: Verify all function calls to `buildPaymentUrl` match the new logic.

# Test: Search for the function usage. Expect: Only occurrences of the new logic.
rg --type ts -A 5 $'buildPaymentUrl'

Length of output: 10182


Line range hint 296-296:
LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to verifyIpnCall match the new logic.

test/build-payment-url.test.ts Show resolved Hide resolved
src/vnpay.ts Show resolved Hide resolved
@lehuygiang28 lehuygiang28 merged commit e305e94 into main Jul 20, 2024
7 checks passed
@lehuygiang28 lehuygiang28 deleted the refactor_readable branch July 20, 2024 23:16
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.

1 participant