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

refactor refund, update docs #13

Merged
merged 5 commits into from
May 26, 2024
Merged

refactor refund, update docs #13

merged 5 commits into from
May 26, 2024

Conversation

lehuygiang28
Copy link
Owner

@lehuygiang28 lehuygiang28 commented May 26, 2024

Summary by CodeRabbit

  • New Features

    • Introduced an API for merchants to request refunds through the VNPAY payment gateway.
    • Added new documentation on retrieving bank lists and their attributes.
    • Enhanced the buildPaymentUrl function to include a new parameter for specifying bank codes.
  • Improvements

    • Updated documentation to improve clarity and structure.
    • Added new types to support expanded functionalities in the VNPAY integration.
  • Bug Fixes

    • None reported.
  • Chores

    • Removed outdated metadata from multiple documentation files.
    • Added configuration file for the IPN module.

Copy link

vercel bot commented May 26, 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 May 26, 2024 7:24am

Copy link

coderabbitai bot commented May 26, 2024

Walkthrough

This update introduces significant changes and additions to the VNPay integration documentation and codebase. Key enhancements include a new parameter for specifying bank codes in payment URLs, a detailed guide on retrieving bank lists, and a comprehensive API for processing refunds. The documentation has been restructured, with metadata adjustments and new content for improved clarity and usability.

Changes

Files/Groups Change Summary
docs/docs/02_installation.md Removed metadata sidebar_position: 2 and adjusted heading structure.
docs/docs/03_get-bank-list.md Added new file detailing the retrieval and properties of bank lists for vnp_BankCode.
docs/docs/04_create-payment-url.md Added vnp_BankCode parameter to buildPaymentUrl function.
docs/docs/05_ipn/01_config-ipn.md Removed metadata and refined IPN URL setup content.
docs/docs/05_ipn/02_verify-ipn-call.md Removed metadata, adjusted links, and refined IPN verification content.
docs/docs/05_ipn/_category_.json Introduced JSON configuration for IPN module, defining label and collapsible behavior.
docs/docs/06_verify-return-url.md Removed metadata and focused on verifying return URL post-payment.
docs/docs/07_query-dr.md Removed metadata and restructured heading for querying transaction results.
docs/docs/08_refund.md Added new file introducing refund API, detailing refund transaction initiation and properties.
docs/docs/20_examples.md Removed metadata and restructured document, removing unnecessary lines.
src/types/index.ts Added new types QueryDrResponseFromVNPay, RefundResponse, RefundResponseFromVNPay, and bank.
src/types/refund.type.ts Modified Refund and RefundResponse types, introduced RefundResponseLogger and RefundOptions.
src/utils/common.ts Enhanced generateRandomString to include an optional onlyNumber flag.
src/vnpay.ts Added new types and modified refund method to accept additional parameters, enhanced processing.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant VNPayAPI
    participant BankListService
    participant RefundService
    User->>VNPayAPI: Request to build payment URL with vnp_BankCode
    VNPayAPI->>BankListService: Retrieve bank list
    BankListService-->>VNPayAPI: Return bank list
    VNPayAPI-->>User: Provide payment URL

    User->>VNPayAPI: Request refund
    VNPayAPI->>RefundService: Process refund request
    RefundService-->>VNPayAPI: Refund response
    VNPayAPI-->>User: Provide refund response
Loading

Tip

Early Access Features
  • Sequence Diagrams in the Walkthrough

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.

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 full the 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 help to get help.

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

CodeRabbit Configration 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.

@lehuygiang28 lehuygiang28 changed the title Update docs refactor refund, update docs May 26, 2024
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: 9

Outside diff range and nitpick comments (10)
docs/docs/05_ipn/01_config-ipn.md (1)

Line range hint 1-20: The instructions for configuring the IPN URL are detailed and clear. Consider adding blank lines around list items for better readability and adherence to Markdown best practices.

+ 1. Đăng nhập vào merchant portal của VNPay tại [đây](https://sandbox.vnpayment.vn/merchantv2/Users/Login.htm)
+
+ 2. Tại góc trên bên phải, chọn thông tin tài khoản:
docs/docs/06_verify-return-url.md (5)

Line range hint 4-4: The description should be more detailed to explain the purpose and importance of the vnp_ReturnUrl.


Line range hint 8-8: Consider adding a brief explanation of what VerifyReturnUrl does to help readers understand its role in the verification process.


Line range hint 20-20: The example code should include error handling for potential exceptions that might occur during the URL verification process.

try {
  const verify: VerifyReturnUrl = vnpay.verifyReturnUrl(req.query);
  // Handle successful verification
} catch (error) {
  // Handle errors
}

Line range hint 24-24: The properties of VerifyReturnUrl should be listed in a table format for better readability and quick reference.


Line range hint 37-37: The example for Express MVC lacks error handling in the route. Consider adding error handling to improve robustness.

app.get('/vnpay-return', async (req, res) => {
  try {
    let verify: VerifyReturnUrl = await vnpay.verifyReturnUrl(req.query);
    if (!verify.isVerified) {
      return res.status(400).send('Verification failed');
    }
    // Further processing
  } catch (error) {
    return res.status(500).send('Internal Server Error');
  }
});
src/utils/common.ts (1)

Line range hint 108-114: Avoid reassigning function parameters as it can lead to confusing and hard-to-track bugs. Consider using local variables instead.

export function resolveUrlString(originalHost: string, originalPath: string): string {
  let host = originalHost.trim();
  let path = originalPath.trim();
  while (host.endsWith('/') || host.endsWith('\\')) {
    host = host.slice(0, -1);
  }
  while (path.startsWith('/') || path.startsWith('\\')) {
    path = path.slice(1);
  }
  return `${host}/${path}`;
}
src/vnpay.ts (3)

Line range hint 162-169: Consider using a for...of loop instead of forEach for better performance and readability.

- bankList.forEach(
-     (b) =>
-         (b.logo_link = resolveUrlString(
-             this.globalDefaultConfig.vnpayHost ?? VNPAY_GATEWAY_SANDBOX_HOST,
-             b.logo_link.slice(1),
-         )),
- );
+ for (const b of bankList) {
+     b.logo_link = resolveUrlString(
+         this.globalDefaultConfig.vnpayHost ?? VNPAY_GATEWAY_SANDBOX_HOST,
+         b.logo_link.slice(1),
+     );
+ }

Line range hint 206-216: Consider using a for...of loop instead of forEach for better performance and readability when appending URL parameters.

- Object.entries(dataToBuild)
-     .sort(([key1], [key2]) => key1.toString().localeCompare(key2.toString()))
-     .forEach(([key, value]) => {
-         if (!value || value === '' || value === undefined || value === null) {
-             return;
-         }
-         redirectUrl.searchParams.append(key, value.toString());
-     });
+ for (const [key, value] of Object.entries(dataToBuild).sort(([key1], [key2]) => key1.toString().localeCompare(key2.toString()))) {
+     if (value && value !== '' && value !== undefined && value !== null) {
+         redirectUrl.searchParams.append(key, value.toString());
+     }
+ }

Line range hint 430-430: Use strict equality checks (===) instead of loose equality checks (==).

- isSuccess: responseData.vnp_ResponseCode == '00',
+ isSuccess: responseData.vnp_ResponseCode === '00',
- Number(responseData.vnp_ResponseCode) <= 90 &&
- Number(responseData.vnp_ResponseCode) >= 99
+ Number(responseData.vnp_ResponseCode) <= 90 &&
+ Number(responseData.vnp_ResponseCode) >= 99

Also applies to: 571-571

Review Details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE

Commits Files that changed from the base of the PR and between d7540fc and 7e5dc38.
Files selected for processing (14)
  • docs/docs/02_installation.md (1 hunks)
  • docs/docs/03_get-bank-list.md (1 hunks)
  • docs/docs/04_create-payment-url.md (2 hunks)
  • docs/docs/05_ipn/01_config-ipn.md (1 hunks)
  • docs/docs/05_ipn/02_verify-ipn-call.md (2 hunks)
  • docs/docs/05_ipn/category.json (1 hunks)
  • docs/docs/06_verify-return-url.md (1 hunks)
  • docs/docs/07_query-dr.md (1 hunks)
  • docs/docs/08_refund.md (1 hunks)
  • docs/docs/20_examples.md (1 hunks)
  • src/types/index.ts (1 hunks)
  • src/types/refund.type.ts (3 hunks)
  • src/utils/common.ts (1 hunks)
  • src/vnpay.ts (4 hunks)
Additional Context Used
Markdownlint (5)
docs/docs/02_installation.md (3)

8: null
Dollar signs used before commands without showing output


14: null
Dollar signs used before commands without showing output


20: null
Dollar signs used before commands without showing output

docs/docs/04_create-payment-url.md (1)

38: null
Bare URL used

docs/docs/05_ipn/01_config-ipn.md (1)

10: null
Lists should be surrounded by blank lines

Biome (32)
src/types/refund.type.ts (5)

1-1: All these imports are only used as types.


1-2: All these imports are only used as types.


2-3: All these imports are only used as types.


3-4: All these imports are only used as types.


4-5: All these imports are only used as types.

src/utils/common.ts (14)

4-4: A Node.js builtin module should be imported with the node: protocol.


97-97: This type annotation is trivially inferred from its initialization.


2-3: Some named imports are only used as types.


3-4: Some named imports are only used as types.


46-46: Use Number.parseInt instead of the equivalent global.


47-47: Use Number.parseInt instead of the equivalent global.


48-48: Use Number.parseInt instead of the equivalent global.


49-49: Use Number.parseInt instead of the equivalent global.


50-50: Use Number.parseInt instead of the equivalent global.


51-51: Use Number.parseInt instead of the equivalent global.


108-108: Reassigning a function parameter is confusing.


110-111: Reassigning a function parameter is confusing.


109-109: Reassigning a function parameter is confusing.


114-114: Reassigning a function parameter is confusing.

src/vnpay.ts (13)

162-169: Prefer for...of instead of forEach.


164-169: The assignment should not be in an expression.


206-216: Prefer for...of instead of forEach.


275-286: Prefer for...of instead of forEach.


430-430: Use === instead of ==.
== is only allowed when comparing against null


571-571: Use === instead of ==.
== is only allowed when comparing against null


635-646: Prefer for...of instead of forEach.


21-34: All these imports are only used as types.


34-42: All these imports are only used as types.


42-49: All these imports are only used as types.


49-50: All these imports are only used as types.


50-51: All these imports are only used as types.


52-53: All these imports are only used as types.

Path-based Instructions (13)
src/types/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.

docs/docs/20_examples.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

docs/docs/03_get-bank-list.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

docs/docs/02_installation.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

docs/docs/05_ipn/01_config-ipn.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

docs/docs/06_verify-return-url.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

src/types/refund.type.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/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.

docs/docs/05_ipn/02_verify-ipn-call.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

docs/docs/07_query-dr.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

docs/docs/08_refund.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

docs/docs/04_create-payment-url.md (1)

Pattern **/*.md: Review the Markdown files to ensure they are well-structured follow Docusaurus's best practices, easy to read, and contain accurate and up-to-date information. Check for proper formatting, grammar, and spelling. Ensure that the content is relevant and engaging for the target audience. Highlight any inconsistencies or errors and suggest improvements to enhance the overall quality of the documentation.

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.

Additional comments not posted (10)
docs/docs/05_ipn/_category_.json (1)

1-5: The JSON configuration for the IPN category is correctly structured and meets the documentation requirements.

src/types/index.ts (1)

5-10: The updates to the export statements correctly reflect the newly added types and maintain consistency with the TypeScript best practices.

docs/docs/20_examples.md (1)

Line range hint 1-12: The examples section is well-structured, providing clear and direct links to further resources, enhancing the usability of the documentation.

docs/docs/03_get-bank-list.md (1)

1-29: The documentation for retrieving the bank list is clear and informative. The included TypeScript code snippet is correctly implemented and enhances the understanding of the API usage.

docs/docs/02_installation.md (1)

Line range hint 1-34: The installation instructions are clear and concise. The use of dollar signs before commands is a common practice in documentation to indicate that these are command line inputs, not outputs.

src/types/refund.type.ts (3)

7-10: The Refund type definition is well-structured and clearly documents the transaction types and required fields. Good use of TypeScript's utility types for type safety.


39-39: The RefundResponseFromVNPay type is comprehensive and well-documented. Ensure that all these fields are consistently used in the backend logic.


83-94: The RefundOptions type is a good example of advanced TypeScript features like generics and mapped types. Ensure that the logger options are properly implemented wherever this type is used.

Verification successful

The RefundOptions type is used in the refund method within src/vnpay.ts. The method signature indicates that RefundOptions is used as an optional parameter for logger fields. However, to ensure that the logger options are properly implemented, we need to verify how options is utilized within the method.


The refund method in src/vnpay.ts properly utilizes the RefundOptions type for logging purposes. The options parameter is passed to the logData method, which handles the logging logic based on the provided options.

  • The logData method checks if the options parameter includes a logger configuration and processes the data accordingly.
  • The refund method constructs the data2Log object and calls logData with this object and the options parameter.

This confirms that the logger options are properly implemented wherever the RefundOptions type is used.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the proper implementation of logger options in RefundOptions.

# Test: Search for the usage of RefundOptions. Expect: Proper implementation of logger options.
rg --type typescript $'RefundOptions'

Length of output: 71



Script:

#!/bin/bash
# Description: Verify the proper implementation of logger options in RefundOptions.

# Test: Search for the usage of RefundOptions. Expect: Proper implementation of logger options.
rg --type ts 'RefundOptions'

Length of output: 233



Script:

#!/bin/bash
# Extract lines containing RefundOptions and surrounding context from src/vnpay.ts
rg --type ts --context 5 'RefundOptions' src/vnpay.ts

Length of output: 805



Script:

#!/bin/bash
# Extract the full implementation of the refund method from src/vnpay.ts
ast-grep --lang typescript --pattern $'class $_ {
  $$$
  public async refund<$_ extends keyof $_>($_, options?: RefundOptions<$_>): Promise<$_> {
    $$$
  }
  $$$
}' src/vnpay.ts

Length of output: 29865

src/utils/common.ts (1)

68-78: The generateRandomString function now correctly handles the generation of numeric-only strings based on the onlyNumber option. This is a useful feature for scenarios requiring numeric strings, such as OTPs.

docs/docs/04_create-payment-url.md (1)

40-40: Ensure the link to the bank list is functional and correct.

Verification successful

The GET request to the URL returned an HTTP 200 status code, indicating that the link is correct and functional.

  • The link to the bank list is valid and leads to a functional page.
Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the link to the bank list is correct and functional.

# Test: Check if the link is correct and leads to a valid page.
curl -I https://sandbox.vnpayment.vn/apis/docs/loai-hang-hoa/

Length of output: 758



Script:

#!/bin/bash
# Description: Verify the link to the bank list is correct and functional.

# Test: Check if the link is correct and leads to a valid page using a GET request.
curl -L -o /dev/null -w "%{http_code}" https://sandbox.vnpayment.vn/apis/docs/loai-hang-hoa/

Length of output: 573

docs/docs/05_ipn/02_verify-ipn-call.md Show resolved Hide resolved
docs/docs/07_query-dr.md Show resolved Hide resolved
docs/docs/08_refund.md Show resolved Hide resolved
@lehuygiang28 lehuygiang28 self-assigned this May 26, 2024
@lehuygiang28 lehuygiang28 merged commit 64ce58c into main May 26, 2024
6 checks passed
@lehuygiang28 lehuygiang28 deleted the refactor_refund_queryDr branch May 26, 2024 07:55
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