-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Chargebee new actions #14906
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
Chargebee new actions #14906
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎ 3 Skipped Deployments
|
WalkthroughThis pull request introduces new modules and functionalities for managing customers and subscriptions in Chargebee. It includes the creation of two actions: one for creating customers and another for creating subscriptions. Each action has defined properties for input and an asynchronous Changes
Assessment against linked issues
Suggested labels
Suggested reviewers
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 6
🧹 Outside diff range and nitpick comments (1)
components/chargebee/common/utils.mjs (1)
1-3: Consider enhancing object cleaning functionality.While the function effectively removes
undefinedvalues, consider extending it to handle:
nullvalues which are often treated similarly toundefinedin API requests- Empty strings which might not be desired in API payloads
- Deep cleaning of nested objects
Here's a more robust implementation:
-export function clearObject(obj) { - return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v !== undefined)); +export function clearObject(obj) { + return Object.fromEntries( + Object.entries(obj).filter(([, value]) => { + return value !== undefined && + value !== null && + value !== ''; + }) + ); +}🧰 Tools
🪛 eslint
[error] 2-2: A linebreak is required after '['.
(array-bracket-newline)
[error] 2-2: '_' is defined but never used.
(no-unused-vars)
[error] 2-2: There should be a linebreak after this element.
(array-element-newline)
[error] 2-2: A linebreak is required before ']'.
(array-bracket-newline)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
components/chargebee/actions/create-customer/create-customer.mjs(1 hunks)components/chargebee/actions/create-subscription/create-subscription.mjs(1 hunks)components/chargebee/chargebee.app.mjs(2 hunks)components/chargebee/common/utils.mjs(1 hunks)components/chargebee/package.json(2 hunks)
🧰 Additional context used
🪛 eslint
components/chargebee/common/utils.mjs
[error] 2-2: A linebreak is required after '['.
(array-bracket-newline)
[error] 2-2: '_' is defined but never used.
(no-unused-vars)
[error] 2-2: There should be a linebreak after this element.
(array-element-newline)
[error] 2-2: A linebreak is required before ']'.
(array-bracket-newline)
components/chargebee/chargebee.app.mjs
[error] 14-14: Strings must use doublequote.
(quotes)
[error] 14-14: Strings must use doublequote.
(quotes)
[error] 17-18: Missing trailing comma.
(comma-dangle)
[error] 18-19: Missing trailing comma.
(comma-dangle)
components/chargebee/actions/create-customer/create-customer.mjs
[error] 63-63: A linebreak is required after '['.
(array-bracket-newline)
[error] 63-63: '_' is defined but never used.
(no-unused-vars)
[error] 63-63: There should be a linebreak after this element.
(array-element-newline)
[error] 63-63: A linebreak is required before ']'.
(array-bracket-newline)
components/chargebee/actions/create-subscription/create-subscription.mjs
[error] 16-17: Missing trailing comma.
(comma-dangle)
🔇 Additional comments (4)
components/chargebee/package.json (1)
14-14: Verify compatibility with platform v3.x
The update from @pipedream/platform v1.x to v3.x is a major version jump that might include breaking changes.
Let's check for any breaking changes:
✅ Verification successful
Platform v3.x is widely adopted across components
The @pipedream/platform v3.x is already being used by 190+ components in the repository, indicating it's a stable and well-tested version. The update from v1.x to v3.x in the chargebee component aligns with the platform version used across the codebase.
Platform v3.x update is safe to proceed
The component only uses the ConfigurationError from @pipedream/platform, which is a stable API that hasn't changed across major versions. The usage is straightforward in both webhook.mjs and base.mjs files, following common patterns seen across other components. The update aligns with the widely adopted v3.x version in the repository.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for migration guides or breaking changes in the platform
gh api repos/PipedreamHQ/pipedream/releases | jq -r '.[] | select(.tag_name | contains("@pipedream/platform@3.0")) | .body'
# Verify if other components are using the same version
rg -l '"@pipedream/platform": "\^3' components/
Length of output: 9272
Script:
#!/bin/bash
# Let's check the component's code for any platform-specific API usage
rg -l "@pipedream/platform" components/chargebee/
rg -A 5 -B 5 "require\(.*@pipedream/platform" components/chargebee/
Length of output: 246
Script:
#!/bin/bash
# Let's examine the platform usage in the component's files
cat components/chargebee/sources/common/webhook.mjs components/chargebee/sources/common/base.mjs
# Also check for any imports/usage of platform features
rg -A 2 "import.*@pipedream/platform" components/chargebee/
Length of output: 2025
components/chargebee/chargebee.app.mjs (1)
46-51: Verify Chargebee API version compatibility.
Ensure the implemented methods align with the Chargebee API version specified in the dependency.
✅ Verification successful
The implemented methods are compatible with Chargebee API version ^2.22.3
The code is using standard Chargebee Node.js SDK methods that are supported in version 2.22.3:
customer.create()for creating customerssubscription.create_for_customer()for creating subscriptions- All methods follow the correct pattern of
.request()to execute the API calls
The implementation aligns perfectly with the Chargebee SDK version specified in package.json ("chargebee": "^2.22.3").
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check Chargebee API version compatibility
rg -l 'chargebee.*\^2\.22\.3' components/
rg -A 5 'configure\({' components/chargebee/
Length of output: 212
Script:
#!/bin/bash
# Check package.json for Chargebee version
cat components/chargebee/package.json
# Check Chargebee configuration and API usage
rg -A 5 'configure\(' components/chargebee/
rg -A 5 'instance\(' components/chargebee/
# Look for any API version configuration
rg -i 'api.*version|version.*api' components/chargebee/
Length of output: 3225
components/chargebee/actions/create-customer/create-customer.mjs (1)
1-9: LGTM! Action metadata is well-defined.
The imports and action metadata are properly configured with appropriate documentation links and versioning.
components/chargebee/actions/create-subscription/create-subscription.mjs (1)
1-9: LGTM! Action metadata and imports are well-defined.
The imports, utility functions, and action metadata are properly configured with appropriate documentation links and versioning.
components/chargebee/actions/create-subscription/create-subscription.mjs
Show resolved
Hide resolved
components/chargebee/actions/create-subscription/create-subscription.mjs
Show resolved
Hide resolved
There was a problem hiding this 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 (2)
components/chargebee/common/utils.mjs (1)
1-6: Enhance object cleaning functionalityThe current implementation only filters
undefinedvalues. Consider enhancing it to handle more edge cases:
- Filter out
nullvalues- Optionally trim and filter empty strings
- Simplify the parameter destructuring
-export function clearObject(obj) { - return Object.fromEntries(Object.entries(obj).filter(([ - _, - v, - ]) => v !== undefined)); +export function clearObject(obj, options = { removeEmpty: false }) { + return Object.fromEntries( + Object.entries(obj).filter(([_, value]) => { + if (value === undefined || value === null) return false; + if (options.removeEmpty && typeof value === 'string' && !value.trim()) return false; + return true; + }) + ); }🧰 Tools
🪛 eslint
[error] 3-3: '_' is defined but never used.
(no-unused-vars)
🪛 GitHub Check: Lint Code Base
[failure] 3-3:
'_' is defined but never usedcomponents/chargebee/actions/create-customer/create-customer.mjs (1)
9-53: Add billing address fieldsSince this customer object will be used for subscriptions, it's important to include billing address fields.
props: { // ... existing props + billingAddress: { + type: "object", + label: "Billing Address", + description: "Billing address details for the customer.", + optional: true, + properties: { + line1: { type: "string", label: "Address Line 1" }, + city: { type: "string", label: "City" }, + state: { type: "string", label: "State" }, + country: { type: "string", label: "Country" }, + zip: { type: "string", label: "ZIP/Postal Code" }, + }, + }, additionalFields: { // ... existing additionalFields }, },
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (4)
components/chargebee/actions/create-customer/create-customer.mjs(1 hunks)components/chargebee/actions/create-subscription/create-subscription.mjs(1 hunks)components/chargebee/chargebee.app.mjs(2 hunks)components/chargebee/common/utils.mjs(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- components/chargebee/chargebee.app.mjs
🧰 Additional context used
🪛 eslint
components/chargebee/actions/create-customer/create-customer.mjs
[error] 64-64: '_' is defined but never used.
(no-unused-vars)
components/chargebee/common/utils.mjs
[error] 3-3: '_' is defined but never used.
(no-unused-vars)
🪛 GitHub Check: Lint Code Base
components/chargebee/actions/create-customer/create-customer.mjs
[failure] 64-64:
'_' is defined but never used
components/chargebee/common/utils.mjs
[failure] 3-3:
'_' is defined but never used
🔇 Additional comments (1)
components/chargebee/actions/create-subscription/create-subscription.mjs (1)
43-54:
Fix critical issues in subscription creation
The previous review already identified the critical issue of using createCustomer instead of createSubscription. Additionally:
- Missing required subscription fields in the request
- No error handling
- No validation of API response
Apply this fix:
async run({ $ }) {
+ if (!this.itemPriceIds?.length) {
+ throw new Error("At least one item price ID is required");
+ }
+
+ const subscriptionData = clearObject({
+ customer_id: this.customerId,
+ subscription_items: this.itemPriceIds.map(id => ({
+ item_price_id: id,
+ })),
id: this.id,
net_term_days: this.netTermDays,
start_date: this.startDate && (Date.parse(this.startDate) / 1000),
+ billing_period: this.billingPeriod,
+ billing_period_unit: this.billingPeriodUnit,
...this.additionalFields,
});
+ try {
+ const response = await this.chargebee.createSubscription(subscriptionData);
+ if (!response?.subscription?.id) {
+ throw new Error("Invalid response from Chargebee API");
+ }
$.export("$summary", `Successfully created subscription (ID: ${response?.subscription?.id})`);
return response;
+ } catch (error) {
+ throw new Error(`Failed to create subscription: ${error.message}`);
+ }
}
components/chargebee/actions/create-subscription/create-subscription.mjs
Show resolved
Hide resolved
jcortes
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @GTFalcao lgtm! Ready for QA!
There was a problem hiding this 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 (1)
components/chargebee/actions/create-subscription/create-subscription.mjs (1)
61-81: Resolve indentation and formatting issuesStatic analysis has identified multiple indentation errors and missing semicolons in the code block from lines 61 to 81. Adjusting the code to align with the project's coding standards enhances readability and prevents potential syntax issues.
Consider applying the recommended fixes from the linter to address these issues.
🧰 Tools
🪛 eslint
[error] 61-61: Expected indentation of 6 spaces but found 4.
(indent)
[error] 62-62: Expected indentation of 8 spaces but found 6.
(indent)
[error] 63-63: Expected indentation of 8 spaces but found 6.
(indent)
[error] 64-64: Expected indentation of 8 spaces but found 6.
(indent)
[error] 65-65: Expected indentation of 8 spaces but found 6.
(indent)
[error] 66-66: Expected indentation of 10 spaces but found 8.
(indent)
[error] 67-67: Expected indentation of 12 spaces but found 10.
(indent)
[error] 68-68: Expected indentation of 12 spaces but found 10.
(indent)
[error] 69-69: Expected indentation of 12 spaces but found 10.
(indent)
[error] 70-70: Expected indentation of 12 spaces but found 10.
(indent)
[error] 71-71: Expected indentation of 10 spaces but found 8.
(indent)
[error] 71-72: Missing trailing comma.
(comma-dangle)
[error] 72-72: Expected indentation of 8 spaces but found 6.
(indent)
[error] 73-73: Expected indentation of 8 spaces but found 6.
(indent)
[error] 74-74: Expected indentation of 6 spaces but found 4.
(indent)
[error] 76-76: Expected indentation of 6 spaces but found 4.
(indent)
[error] 77-77: Expected indentation of 6 spaces but found 4.
(indent)
[error] 78-78: Expected indentation of 4 spaces but found 2.
(indent)
[error] 79-79: Expected indentation of 6 spaces but found 4.
(indent)
[error] 80-80: Expected indentation of 6 spaces but found 4.
(indent)
[error] 80-81: Missing semicolon.
(semi)
[error] 81-81: Expected indentation of 4 spaces but found 2.
(indent)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (25)
components/chargebee/actions/create-customer/create-customer.mjs(1 hunks)components/chargebee/actions/create-subscription/create-subscription.mjs(1 hunks)components/chargebee/chargebee.app.mjs(1 hunks)components/chargebee/common/utils.mjs(1 hunks)components/chargebee/package.json(2 hunks)components/chargebee/sources/customer-card-expired-instant/customer-card-expired-instant.mjs(1 hunks)components/chargebee/sources/customer-changed-instant/customer-changed-instant.mjs(1 hunks)components/chargebee/sources/new-customer-created-instant/new-customer-created-instant.mjs(1 hunks)components/chargebee/sources/new-event/new-event.mjs(1 hunks)components/chargebee/sources/new-invoice-created-instant/new-invoice-created-instant.mjs(1 hunks)components/chargebee/sources/new-invoice-updated-instant/new-invoice-updated-instant.mjs(1 hunks)components/chargebee/sources/new-payment-source-added-instant/new-payment-source-added-instant.mjs(1 hunks)components/chargebee/sources/payment-failed-instant/payment-failed-instant.mjs(1 hunks)components/chargebee/sources/payment-refunded-instant/payment-refunded-instant.mjs(1 hunks)components/chargebee/sources/payment-source-updated-instant/payment-source-updated-instant.mjs(1 hunks)components/chargebee/sources/payment-succeeded-instant/payment-succeeded-instant.mjs(1 hunks)components/chargebee/sources/subscription-activated-instant/subscription-activated-instant.mjs(1 hunks)components/chargebee/sources/subscription-cancellation-scheduled-instant/subscription-cancellation-scheduled-instant.mjs(1 hunks)components/chargebee/sources/subscription-cancelled-instant/subscription-cancelled-instant.mjs(1 hunks)components/chargebee/sources/subscription-changed-instant/subscription-changed-instant.mjs(1 hunks)components/chargebee/sources/subscription-created-instant/subscription-created-instant.mjs(1 hunks)components/chargebee/sources/subscription-paused-instant/subscription-paused-instant.mjs(1 hunks)components/chargebee/sources/subscription-reactivated-instant/subscription-reactivated-instant.mjs(1 hunks)components/chargebee/sources/subscription-renewed-instant/subscription-renewed-instant.mjs(1 hunks)components/chargebee/sources/subscription-resumed-instant/subscription-resumed-instant.mjs(1 hunks)
✅ Files skipped from review due to trivial changes (20)
- components/chargebee/sources/subscription-paused-instant/subscription-paused-instant.mjs
- components/chargebee/sources/subscription-resumed-instant/subscription-resumed-instant.mjs
- components/chargebee/sources/subscription-cancelled-instant/subscription-cancelled-instant.mjs
- components/chargebee/sources/payment-succeeded-instant/payment-succeeded-instant.mjs
- components/chargebee/sources/subscription-changed-instant/subscription-changed-instant.mjs
- components/chargebee/sources/payment-refunded-instant/payment-refunded-instant.mjs
- components/chargebee/sources/subscription-renewed-instant/subscription-renewed-instant.mjs
- components/chargebee/sources/new-customer-created-instant/new-customer-created-instant.mjs
- components/chargebee/sources/new-payment-source-added-instant/new-payment-source-added-instant.mjs
- components/chargebee/sources/subscription-activated-instant/subscription-activated-instant.mjs
- components/chargebee/sources/new-invoice-updated-instant/new-invoice-updated-instant.mjs
- components/chargebee/sources/new-invoice-created-instant/new-invoice-created-instant.mjs
- components/chargebee/sources/subscription-created-instant/subscription-created-instant.mjs
- components/chargebee/sources/new-event/new-event.mjs
- components/chargebee/sources/subscription-reactivated-instant/subscription-reactivated-instant.mjs
- components/chargebee/sources/payment-failed-instant/payment-failed-instant.mjs
- components/chargebee/sources/payment-source-updated-instant/payment-source-updated-instant.mjs
- components/chargebee/sources/customer-changed-instant/customer-changed-instant.mjs
- components/chargebee/sources/subscription-cancellation-scheduled-instant/subscription-cancellation-scheduled-instant.mjs
- components/chargebee/sources/customer-card-expired-instant/customer-card-expired-instant.mjs
🚧 Files skipped from review as they are similar to previous changes (2)
- components/chargebee/common/utils.mjs
- components/chargebee/package.json
🧰 Additional context used
🪛 eslint
components/chargebee/chargebee.app.mjs
[error] 25-25: Expected a line break after this opening brace.
(object-curly-newline)
[error] 25-25: Expected a line break before this closing brace.
(object-curly-newline)
components/chargebee/actions/create-subscription/create-subscription.mjs
[error] 21-22: Missing trailing comma.
(comma-dangle)
[error] 61-61: Expected indentation of 6 spaces but found 4.
(indent)
[error] 62-62: Expected indentation of 8 spaces but found 6.
(indent)
[error] 63-63: Expected indentation of 8 spaces but found 6.
(indent)
[error] 64-64: Expected indentation of 8 spaces but found 6.
(indent)
[error] 65-65: Expected indentation of 8 spaces but found 6.
(indent)
[error] 66-66: Expected indentation of 10 spaces but found 8.
(indent)
[error] 67-67: Expected indentation of 12 spaces but found 10.
(indent)
[error] 68-68: Expected indentation of 12 spaces but found 10.
(indent)
[error] 69-69: Expected indentation of 12 spaces but found 10.
(indent)
[error] 70-70: Expected indentation of 12 spaces but found 10.
(indent)
[error] 71-71: Expected indentation of 10 spaces but found 8.
(indent)
[error] 71-72: Missing trailing comma.
(comma-dangle)
[error] 72-72: Expected indentation of 8 spaces but found 6.
(indent)
[error] 73-73: Expected indentation of 8 spaces but found 6.
(indent)
[error] 74-74: Expected indentation of 6 spaces but found 4.
(indent)
[error] 76-76: Expected indentation of 6 spaces but found 4.
(indent)
[error] 77-77: Expected indentation of 6 spaces but found 4.
(indent)
[error] 78-78: Expected indentation of 4 spaces but found 2.
(indent)
[error] 79-79: Expected indentation of 6 spaces but found 4.
(indent)
[error] 80-80: Expected indentation of 6 spaces but found 4.
(indent)
[error] 80-81: Missing semicolon.
(semi)
[error] 81-81: Expected indentation of 4 spaces but found 2.
(indent)
🔇 Additional comments (5)
components/chargebee/actions/create-subscription/create-subscription.mjs (1)
40-51: 🛠️ Refactor suggestion
Add validation for netTermDays and startDate
The properties netTermDays and startDate lack validation. Adding validation ensures that input values are within expected ranges and formats.
Consider adding the following validation:
netTermDays: {
type: "integer",
label: "Net Term Days",
description: "Defines [Net D](https://www.chargebee.com/docs/net_d.html?_gl=1*1w075xz*_gcl_au*MTU4NzU2NDYzOC4xNzMzODA0OTYw) for the subscription. Net D is the number of days within which any invoice raised for the subscription must be paid.",
optional: true,
+ min: 0,
+ max: 365, // Assuming one year is the maximum net term
},
startDate: {
type: "string",
label: "Start Date",
description: "The date/time at which the subscription is to start, e.g. `2024-08-15T09:30:00Z`. If not provided, the subscription starts immediately.",
optional: true,
+ validate: (value) => {
+ if (!value) return true;
+ const date = new Date(value);
+ if (isNaN(date.getTime())) {
+ throw new Error("Invalid date format");
+ }
+ if (date < new Date()) {
+ throw new Error("Start date must be in the future");
+ }
+ return true;
+ },
},components/chargebee/chargebee.app.mjs (2)
15-17: 🛠️ Refactor suggestion
Add error handling to customer options retrieval
The options method for customerId should handle potential API errors to prevent breaking the UI when listing customers.
Consider wrapping the API call in a try-catch block:
async options() {
+ try {
const customers = await this.getCustomers();
return customers.list.map(({ customer }) => ({
label: `${customer.first_name ?? ""} ${customer.last_name ?? ""} (${customer.email ?? customer.id})`,
value: customer.id,
}));
+ } catch (err) {
+ console.error('Failed to fetch customers:', err);
+ throw new Error('Failed to fetch customers. Please check your API credentials and try again.');
+ }
},57-62: 🛠️ Refactor suggestion
Add error handling and response validation to API methods
The methods createCustomer and createSubscription lack error handling and response validation. This can lead to unhandled exceptions or unexpected behavior.
Consider updating the methods to handle errors and validate responses:
createCustomer(args = {}) {
+ return this.instance().customer.create(args)
+ .then(response => {
+ if (!response?.customer?.id) {
+ throw new Error('Invalid response: Customer data missing');
+ }
+ return response;
+ })
+ .catch(error => {
+ throw new Error(`Failed to create customer: ${error.message}`);
+ });
},
createSubscription(customerId, args = {}) {
if (!customerId) {
throw new Error('Customer ID is required');
}
+ return this.instance().subscription.createWithItems(customerId, args)
+ .then(response => {
+ if (!response?.subscription?.id) {
+ throw new Error('Invalid response: Subscription data missing');
+ }
+ return response;
+ })
+ .catch(error => {
+ throw new Error(`Failed to create subscription: ${error.message}`);
+ });
},components/chargebee/actions/create-customer/create-customer.mjs (2)
30-41: 🛠️ Refactor suggestion
Add input validation for email and phone fields
While these fields are optional, adding validation ensures that when provided, they are in the correct format.
Consider adding validation like this:
email: {
type: "string",
label: "Email",
description: "Email of the customer.",
optional: true,
+ validate: (value) => {
+ if (!value) return true;
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ if (!emailRegex.test(value)) {
+ throw new Error("Invalid email format");
+ }
+ return true;
+ },
},
phone: {
type: "string",
label: "Phone",
description: "Phone number of the customer.",
optional: true,
+ validate: (value) => {
+ if (!value) return true;
+ // Assuming E.164 format: +[country code][number]
+ const phoneRegex = /^\+[1-9]\d{1,14}$/;
+ if (!phoneRegex.test(value)) {
+ throw new Error("Phone number must be in E.164 format (e.g., +12345678900)");
+ }
+ return true;
+ },55-68: 🛠️ Refactor suggestion
Add error handling for API call
The run method lacks error handling for the API call to createCustomer. Without error handling, any API errors could cause unhandled exceptions.
Consider wrapping the API call in a try-catch block:
async run({ $ }) {
+ try {
const response = await this.chargebee.createCustomer(clearObject({
id: this.id,
first_name: this.firstName,
last_name: this.lastName,
email: this.email,
phone: this.phone,
company: this.company,
...this.additionalFields,
}));
$.export("$summary", `Successfully created customer (ID: ${response?.customer?.id})`);
return response;
+ } catch (error) {
+ $.export("debug", error);
+ throw new Error("Error creating customer. Check the debug export for more information.");
+ }
},Likely invalid or redundant comment.
components/chargebee/actions/create-subscription/create-subscription.mjs
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (1)
components/chargebee/actions/create-subscription/create-subscription.mjs (1)
78-81: Include error message in the thrown errorTo provide more detailed error information, consider including the original error message in the thrown error. This helps in debugging and understanding the root cause of the failure.
Apply this diff to enhance error handling:
} catch (error) { $.export("debug", error); - throw new Error("Error creating subscription. Check the debug export for more information."); + throw new Error(`Error creating subscription: ${error.message}`); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (2)
components/chargebee/actions/create-subscription/create-subscription.mjs(1 hunks)components/chargebee/chargebee.app.mjs(1 hunks)
🔇 Additional comments (3)
components/chargebee/actions/create-subscription/create-subscription.mjs (1)
40-51: 🛠️ Refactor suggestion
Add validation for netTermDays and startDate
To ensure correct input and prevent potential errors, please add validation for the netTermDays and startDate fields.
Apply this diff to implement the validations:
netTermDays: {
type: "integer",
label: "Net Term Days",
description: "Defines [Net D](https://www.chargebee.com/docs/net_d.html?_gl=1*1w075xz*_gcl_au*MTU4NzU2NDYzOC4xNzMzODA0OTYw) for the subscription. Net D is the number of days within which any invoice raised for the subscription must be paid.",
optional: true,
+ min: 0,
+ max: 365, // Assuming a maximum of one year
},
startDate: {
type: "string",
label: "Start Date",
description: "The date/time at which the subscription is to start, e.g. `2024-08-15T09:30:00Z`. If not provided, the subscription starts immediately.",
optional: true,
+ async validate(value) {
+ if (!value) return true;
+ const date = new Date(value);
+ if (isNaN(date.getTime())) {
+ throw new Error("Invalid date format");
+ }
+ if (date < new Date()) {
+ throw new Error("Start date must be in the future");
+ }
+ return true;
+ },
},components/chargebee/chargebee.app.mjs (2)
11-17: 🛠️ Refactor suggestion
Add error handling in customerId options method
To prevent potential errors when fetching customers, add error handling to the options method. This ensures that the UI does not break if the API call fails.
Apply this diff to include error handling:
async options() {
+ try {
const customers = await this.getCustomers();
return customers.list.map(({ customer }) => ({
label: `${customer.first_name ?? ""} ${customer.last_name ?? ""} (${customer.email ?? customer.id})`,
value: customer.id,
}));
+ } catch (error) {
+ console.error('Failed to fetch customers:', error);
+ throw new Error('Failed to fetch customers. Please check your API credentials and try again.');
+ }
},23-33: 🛠️ Refactor suggestion
Add error handling in itemPriceId options method
To handle potential API failures when fetching item prices, include error handling in the options method. This ensures robustness and provides meaningful feedback to the user.
Apply this diff to enhance error handling:
async options() {
+ try {
const itemPrices = await this.getItemPrices();
return itemPrices.list.map(({
item_price: {
name, id,
},
}) => ({
label: name,
value: id,
}));
+ } catch (error) {
+ console.error('Failed to fetch item prices:', error);
+ throw new Error('Failed to fetch item prices. Please check your API credentials and try again.');
+ }
},There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
components/chargebee/actions/create-customer/create-customer.mjs(1 hunks)components/chargebee/actions/create-subscription/create-subscription.mjs(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- components/chargebee/actions/create-customer/create-customer.mjs
🔇 Additional comments (4)
components/chargebee/actions/create-subscription/create-subscription.mjs (4)
1-9: LGTM! Action definition and imports are well structured.
The imports and action metadata are properly defined with clear documentation links.
10-58: Add required subscription-specific fields
The implementation is missing essential fields required for creating a subscription in Chargebee.
24-33: 🛠️ Refactor suggestion
Add validation for price and quantity fields.
The unitPrice and quantity fields should have validation:
- unitPrice should be positive
- quantity should be at least 1
unitPrice: {
type: "integer",
label: "Unit Price",
description: "The unit price of the plan item.",
+ min: 1,
},
quantity: {
type: "integer",
label: "Quantity",
description: "The quantity of the plan item.",
+ min: 1,
},Likely invalid or redundant comment.
75-77: 🛠️ Refactor suggestion
Add response structure validation.
Verify the response structure before accessing nested properties to prevent potential runtime errors.
+ if (!response?.subscription?.id) {
+ throw new Error('Invalid response structure from Chargebee API');
+ }
+
$.export("$summary", `Successfully created subscription (ID: ${response?.subscription?.id})`);
return response;Likely invalid or redundant comment.
components/chargebee/actions/create-subscription/create-subscription.mjs
Show resolved
Hide resolved
There was a problem hiding this 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 (1)
components/chargebee/actions/create-subscription/create-subscription.mjs (1)
78-81: Improve error message specificity.The error message should provide more context about what went wrong.
} catch (error) { $.export("debug", error); - throw new Error(`Error creating subscription: ${error.message}`); + throw new Error( + `Failed to create subscription: ${error.message}. ` + + "Please check the debug export for more details and ensure all required fields are provided correctly." + ); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
components/chargebee/actions/create-subscription/create-subscription.mjs(1 hunks)components/chargebee/chargebee.app.mjs(1 hunks)
🧰 Additional context used
📓 Learnings (1)
components/chargebee/chargebee.app.mjs (1)
Learnt from: GTFalcao
PR: PipedreamHQ/pipedream#14906
File: components/chargebee/chargebee.app.mjs:44-68
Timestamp: 2024-12-11T20:39:04.063Z
Learning: In the new version of the Chargebee module, API method calls already execute the request and return a Promise, so there's no need to call the `.request()` method.
🔇 Additional comments (8)
components/chargebee/chargebee.app.mjs (5)
40-43: LGTM!
The instance method correctly initializes the Chargebee client with the required authentication credentials.
45-62: LGTM!
The API methods are correctly implemented without the .request() call as per the new version of the Chargebee module.
63-71: LGTM!
The new API methods are correctly implemented following the same pattern as existing methods.
11-17: 🛠️ Refactor suggestion
Add error handling to customer options retrieval.
The options method should handle potential API errors to prevent breaking the UI when listing customers.
async options() {
+ try {
const customers = await this.getCustomers();
return customers.list.map(({ customer }) => ({
label: `${customer.first_name ?? ""} ${customer.last_name ?? ""} (${customer.email ?? customer.id})`,
value: customer.id,
}));
+ } catch (error) {
+ console.error('Failed to fetch customers:', error);
+ throw new Error('Failed to fetch customers. Please check your API credentials and try again.');
+ }
},Likely invalid or redundant comment.
23-35: 🛠️ Refactor suggestion
Simplify object destructuring and add error handling.
The implementation can be simplified and should include error handling.
async options() {
+ try {
const itemPrices = await this.getItemPrices();
return itemPrices.list
.filter(({ item_price: { item_type } }) => item_type === "plan")
- .map(({
- item_price: {
- name, id,
- },
- }) => ({
+ .map(({ item_price }) => ({
+ label: item_price.name,
+ value: item_price.id,
+ }));
+ } catch (error) {
+ console.error('Failed to fetch item prices:', error);
+ throw new Error('Failed to fetch item prices. Please check your API credentials and try again.');
+ }
},Likely invalid or redundant comment.
components/chargebee/actions/create-subscription/create-subscription.mjs (3)
59-74: 🛠️ Refactor suggestion
Add input validation and improve error handling.
The run method should validate inputs and API response structure.
async run({ $ }) {
+ // Validate required fields
+ if (!this.itemPriceId || !this.unitPrice || !this.quantity) {
+ throw new Error("itemPriceId, unitPrice, and quantity are required fields");
+ }
+
try {
const response = await this.chargebee.createSubscription(this.customerId, clearObject({
id: this.id,
net_term_days: this.netTermDays,
start_date: this.startDate && (Date.parse(this.startDate) / 1000),
subscription_items: [
{
item_price_id: this.itemPriceId,
item_type: "plan",
unit_price: this.unitPrice,
quantity: this.quantity,
},
],
...this.additionalFields,
}));
+
+ // Validate response structure
+ if (!response?.subscription?.id) {
+ throw new Error("Invalid response from Chargebee API");
+ }Likely invalid or redundant comment.
40-45: 🛠️ Refactor suggestion
Add validation for netTermDays.
The netTermDays field should have a reasonable range to prevent invalid values.
netTermDays: {
type: "integer",
label: "Net Term Days",
description: "Defines [Net D](https://www.chargebee.com/docs/net_d.html?_gl=1*1w075xz*_gcl_au*MTU4NzU2NDYzOC4xNzMzODA0OTYw) for the subscription. Net D is the number of days within which any invoice raised for the subscription must be paid.",
optional: true,
+ min: 0,
+ max: 365, // Assuming one year is maximum net terms
},Likely invalid or redundant comment.
46-51: 🛠️ Refactor suggestion
Add date validation for startDate.
The startDate field should validate the date format and ensure it's in the future.
startDate: {
type: "string",
label: "Start Date",
description: "The date/time at which the subscription is to start, e.g. `2024-08-15T09:30:00Z`. If not provided, the subscription starts immediately.",
optional: true,
+ validate: (value) => {
+ if (!value) return true;
+ const date = new Date(value);
+ if (isNaN(date.getTime())) {
+ throw new Error("Invalid date format");
+ }
+ if (date < new Date()) {
+ throw new Error("Start date must be in the future");
+ }
+ return true;
+ },
},Likely invalid or redundant comment.
|
/approve |
Closes #14857
Summary by CodeRabbit
New Features
Bug Fixes
Chores