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(accept-blue): implemented update subscription #557

Merged
merged 9 commits into from
Jan 10, 2025

Conversation

martijnvdbrug
Copy link
Member

@martijnvdbrug martijnvdbrug commented Jan 7, 2025

Description

  • Allow updating created subscriptions via the Admin API
  • Only allow refunding for users with permission UpdateOrder

Closes #544 and #440

Breaking changes

refundAcceptBlueTransactiuon is now only available to users with permission UpdateOrder

Checklist

📌 Always:

  • Set a clear title
  • I have checked my own PR

👍 Most of the time:

  • Added or updated test cases
  • Updated the README

📦 For publishable packages:

  • Increased the version number in package.json
  • Added changes to the CHANGELOG.md

Copy link
Contributor

coderabbitai bot commented Jan 7, 2025

Walkthrough

This pull request introduces enhancements to the Vendure AcceptBlue plugin, focusing on subscription management and transaction processing. Key changes include the ability to update subscriptions through the Admin API, implementing permission-based controls for refunds, and restructuring API extensions to support distinct admin and shop contexts.

Changes

File Change Summary
.github/CODEOWNERS Added @martijnvdbrug as owner for /packages/vendure-plugin-accept-blue/
packages/vendure-plugin-accept-blue/CHANGELOG.md Updated to version 2.1.0, documenting new subscription and refund capabilities
src/accept-blue-plugin.ts Refactored API extensions to separate admin and shop contexts
src/api/accept-blue-admin-resolver.ts New resolver for admin-specific mutations like refunding and updating subscriptions
src/api/accept-blue-client.ts Added method to update recurring schedules
src/api/accept-blue-service.ts Introduced updateSubscription method with event logging
src/api/api-extensions.ts Updated GraphQL schema with new mutations and input types

Assessment against linked issues

Objective Addressed Explanation
Edit subscription options
Track subscription changes via order mutation events
Access Update recurring schedules API method

Suggested reviewers

Possibly related PRs

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

@mschipperheyn
Copy link
Collaborator

yeah, admin api only

@martijnvdbrug martijnvdbrug marked this pull request as ready for review January 10, 2025 09:30
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
packages/vendure-plugin-accept-blue/src/api/accept-blue-admin-resolver.ts (1)

24-25: Remove redundant null coalescing

The ?? undefined is unnecessary as it's the default behavior of the null coalescing operator.

-      amount ?? undefined,
-      cvv2 ?? undefined
+      amount,
+      cvv2
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7a45f7 and 1ffc307.

⛔ Files ignored due to path filters (1)
  • packages/vendure-plugin-accept-blue/package.json is excluded by !**/*.json
📒 Files selected for processing (13)
  • .github/CODEOWNERS (1 hunks)
  • packages/vendure-plugin-accept-blue/CHANGELOG.md (1 hunks)
  • packages/vendure-plugin-accept-blue/src/accept-blue-plugin.ts (2 hunks)
  • packages/vendure-plugin-accept-blue/src/api/accept-blue-admin-resolver.ts (1 hunks)
  • packages/vendure-plugin-accept-blue/src/api/accept-blue-client.ts (3 hunks)
  • packages/vendure-plugin-accept-blue/src/api/accept-blue-common-resolvers.ts (1 hunks)
  • packages/vendure-plugin-accept-blue/src/api/accept-blue-service.ts (4 hunks)
  • packages/vendure-plugin-accept-blue/src/api/api-extensions.ts (3 hunks)
  • packages/vendure-plugin-accept-blue/src/events/accept-blue-subscription-event.ts (1 hunks)
  • packages/vendure-plugin-accept-blue/src/index.ts (1 hunks)
  • packages/vendure-plugin-accept-blue/src/types.ts (2 hunks)
  • packages/vendure-plugin-accept-blue/test/accept-blue.spec.ts (8 hunks)
  • packages/vendure-plugin-accept-blue/test/helpers/graphql-helpers.ts (2 hunks)
🔇 Additional comments (15)
packages/vendure-plugin-accept-blue/src/events/accept-blue-subscription-event.ts (1)

10-19: LGTM! Clean event implementation.

The event class is well-structured and properly typed.

packages/vendure-plugin-accept-blue/src/accept-blue-plugin.ts (1)

23-24: LGTM! Clean API separation.

The split between admin and shop API extensions is well-implemented.

Also applies to: 27-28

packages/vendure-plugin-accept-blue/src/api/accept-blue-common-resolvers.ts (1)

1-1: LGTM! Clean removal of refund mutation.

The refund functionality has been properly moved to the admin resolver.

packages/vendure-plugin-accept-blue/src/api/api-extensions.ts (3)

Line range hint 9-162: LGTM! Well-structured schema definitions.

The input types and enums are well-documented and properly typed.


164-167: LGTM! Proper API separation.

Good practice separating shop and admin APIs.


168-187: Verify permission checks for admin mutations.

The mutations look good, but ensure they're properly protected with the UpdateOrder permission as mentioned in the PR objectives.

✅ Verification successful

Permission checks are properly implemented

Both admin mutations are correctly protected with @Allow(Permission.UpdateOrder) as required.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for permission checks in the resolver
ast-grep --pattern 'class $_ {
  $$$
  @$_("UpdateOrder")
  $$$
  refundAcceptBlueTransaction($$$) {
    $$$
  }
  $$$
}'

Length of output: 123


Script:

#!/bin/bash
# First find the resolver file
fd resolver packages/vendure-plugin-accept-blue/src

# Then look for the resolver implementation
ast-grep --pattern 'class $_ {
  $$$
  @$_($$$)
  $$$
  refundAcceptBlueTransaction($$$) {
    $$$
  }
  $$$
}'

ast-grep --pattern 'class $_ {
  $$$
  @$_($$$)
  $$$
  updateAcceptBlueSubscription($$$) {
    $$$
  }
  $$$
}'

Length of output: 432


Script:

#!/bin/bash
# Check the admin resolver content
cat packages/vendure-plugin-accept-blue/src/api/accept-blue-admin-resolver.ts

# Backup search for mutations and decorators
rg -A 5 "refundAcceptBlueTransaction|updateAcceptBlueSubscription" packages/vendure-plugin-accept-blue/src/api/accept-blue-admin-resolver.ts

Length of output: 2059

packages/vendure-plugin-accept-blue/src/api/accept-blue-client.ts (2)

136-154: LGTM! Proper amount and date handling.

The implementation correctly handles:

  • Amount conversion from cents
  • Date formatting to yyyy-mm-dd

202-203: LGTM! Type safety improvement.

Good update to use the more specific CreateInput type.

packages/vendure-plugin-accept-blue/src/types.ts (1)

Line range hint 265-291: LGTM! Well-defined types with proper documentation.

Good separation between create and update types, with update type correctly making all fields optional.

packages/vendure-plugin-accept-blue/test/helpers/graphql-helpers.ts (2)

172-186: LGTM! Complete history query.

The query includes all necessary fields for testing order history.


242-254: LGTM! Comprehensive subscription update mutation.

The mutation includes all necessary fields to test subscription updates.

packages/vendure-plugin-accept-blue/src/api/accept-blue-service.ts (1)

67-68: LGTM!

The constructor changes follow best practices by making dependencies explicit and using readonly where appropriate.

packages/vendure-plugin-accept-blue/CHANGELOG.md (1)

1-4: LGTM!

The changelog entries accurately describe the implemented changes.

.github/CODEOWNERS (1)

5-5: LGTM!

The CODEOWNERS entry is correctly formatted and properly adds the new owner.

packages/vendure-plugin-accept-blue/src/index.ts (1)

7-8: Verify file locations after restructuring

The event files have been moved to a new directory structure.

Let's verify the file locations:

✅ Verification successful

Files verified in new location

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the event files exist in their new location
fd --type f "accept-blue-(transaction|subscription)-event.ts" packages/vendure-plugin-accept-blue/src/events

Length of output: 271

Comment on lines 328 to 331
const subcription = this.mapToGraphqlSubscription(
subscription,
orderLine.productVariant.id
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in variable name

The variable name subcription is misspelled.

-    const subcription = this.mapToGraphqlSubscription(
+    const subscription = this.mapToGraphqlSubscription(
       subscription,
       orderLine.productVariant.id
     );
📝 Committable suggestion

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

Suggested change
const subcription = this.mapToGraphqlSubscription(
subscription,
orderLine.productVariant.id
);
const subscription = this.mapToGraphqlSubscription(
subscription,
orderLine.productVariant.id
);

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/vendure-plugin-accept-blue/README.md (1)

180-180: Fix typo in the text

Change "de admin-api" to "the admin-api"

-You can update created subscriptions in Accept Blue as Admin via de admin-api with `UpdateOrder` permissions:
+You can update created subscriptions in Accept Blue as Admin via the admin-api with `UpdateOrder` permissions:
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ffc307 and a5190df.

📒 Files selected for processing (1)
  • packages/vendure-plugin-accept-blue/README.md (1 hunks)

packages/vendure-plugin-accept-blue/README.md Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
packages/vendure-plugin-accept-blue/src/api/accept-blue-service.ts (2)

328-331: ⚠️ Potential issue

Fix typo in variable name

The variable name subcription is misspelled.

-    const subcription = this.mapToGraphqlSubscription(
+    const subscription = this.mapToGraphqlSubscription(
       subscription,
       orderLine.productVariant.id
     );

339-343: ⚠️ Potential issue

Fix propagated typo in event publishing

The misspelled variable is used in event publishing.

     await this.eventBus.publish(
-      new AcceptBlueSubscriptionEvent(ctx, subcription, 'updated', input)
+      new AcceptBlueSubscriptionEvent(ctx, subscription, 'updated', input)
     );
-    return subcription;
+    return subscription;
🧹 Nitpick comments (2)
packages/vendure-plugin-accept-blue/CHANGELOG.md (1)

8-8: Fix typo in changelog

There's a typo in "Piublicly".

-Piublicly expose ctx in AcceptBlueTransactionEvent
+Publicly expose ctx in AcceptBlueTransactionEvent
packages/vendure-plugin-accept-blue/src/api/accept-blue-service.ts (1)

333-337: Consider adding more detailed update notes

The order note could be more specific about which fields were updated.

-      note: `Subscription updated: ${JSON.stringify(input)}`,
+      note: `Subscription ${input.id} updated: ${Object.entries(input)
+        .filter(([key, value]) => value !== undefined && key !== 'id')
+        .map(([key, value]) => `${key}=${value}`)
+        .join(', ')}`,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a5190df and 89834e7.

📒 Files selected for processing (3)
  • packages/vendure-plugin-accept-blue/CHANGELOG.md (1 hunks)
  • packages/vendure-plugin-accept-blue/src/api/accept-blue-service.ts (4 hunks)
  • packages/vendure-plugin-accept-blue/src/types.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: packages/vendure-plugin-stripe-subscription/
  • GitHub Check: packages/vendure-plugin-stock-monitoring/
  • GitHub Check: packages/vendure-plugin-shipping-extensions/
  • GitHub Check: packages/vendure-plugin-shipmate/
  • GitHub Check: packages/vendure-plugin-sendcloud/
  • GitHub Check: packages/vendure-plugin-public-customer-groups/
  • GitHub Check: packages/vendure-plugin-primary-collection/
  • GitHub Check: packages/vendure-plugin-popularity-scores/
  • GitHub Check: packages/vendure-plugin-picqer/
  • GitHub Check: packages/vendure-plugin-picklist/
  • GitHub Check: packages/vendure-plugin-myparcel/
  • GitHub Check: packages/vendure-plugin-multiserver-db-sessioncache/
  • GitHub Check: packages/vendure-plugin-modify-customer-orders/
  • GitHub Check: packages/vendure-plugin-coinbase/
  • GitHub Check: packages/vendure-plugin-anonymized-order/
  • GitHub Check: packages/vendure-plugin-admin-ui-helpers/
  • GitHub Check: packages/vendure-plugin-admin-social-auth/
  • GitHub Check: packages/util/
  • GitHub Check: packages/test/
  • GitHub Check: Prettier formatting
🔇 Additional comments (3)
packages/vendure-plugin-accept-blue/src/types.ts (2)

Line range hint 267-280: LGTM! Well-structured create interface.

The interface correctly defines required and optional fields for creating recurring schedules.


281-293: LGTM! Well-structured update interface.

The interface properly makes all fields optional to support partial updates of recurring schedules.

packages/vendure-plugin-accept-blue/src/api/accept-blue-service.ts (1)

319-327: ⚠️ Potential issue

Fix boolean handling in updateRecurringSchedule

The || operator will override false values with undefined. Use nullish coalescing (??) instead.

    const subscription = await client.updateRecurringSchedule(scheduleId, {
      title: input.title || undefined,
      amount: input.amount || undefined,
      frequency: input.frequency ?? undefined,
      next_run_date: input.nextRunDate || undefined,
      num_left: input.numLeft || undefined,
-     active: input.active || undefined,
+     active: input.active ?? undefined,
      receipt_email: input.receiptEmail || undefined,
    });

Likely invalid or redundant comment.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/vendure-plugin-accept-blue/test/accept-blue.spec.ts (1)

625-627: ⚠️ Potential issue

Add 'await' before expect

The assertion needs to be awaited for proper async error handling.

Apply this diff to fix the issue:

-    expect(updateRequest).rejects.toThrowError(
+    await expect(updateRequest).rejects.toThrowError(
🧹 Nitpick comments (1)
packages/vendure-plugin-accept-blue/test/accept-blue.spec.ts (1)

680-682: Add type safety to history entry filtering

The type assertion is unsafe and could lead to runtime errors.

Apply this diff to add type safety:

-    const entry = order.history.items.find(
-      (entry: any) => entry.type === 'ORDER_NOTE'
-    );
+    interface HistoryEntry {
+      type: string;
+      data: {
+        note: string;
+      };
+    }
+    const entry = order.history.items.find(
+      (entry: HistoryEntry) => entry.type === 'ORDER_NOTE'
+    );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89834e7 and 67c7adb.

📒 Files selected for processing (4)
  • packages/vendure-plugin-accept-blue/CHANGELOG.md (1 hunks)
  • packages/vendure-plugin-accept-blue/README.md (1 hunks)
  • packages/vendure-plugin-accept-blue/src/api/accept-blue-service.ts (4 hunks)
  • packages/vendure-plugin-accept-blue/test/accept-blue.spec.ts (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/vendure-plugin-accept-blue/README.md
  • packages/vendure-plugin-accept-blue/CHANGELOG.md
  • packages/vendure-plugin-accept-blue/src/api/accept-blue-service.ts
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: packages/vendure-plugin-stripe-subscription/
  • GitHub Check: packages/vendure-plugin-stock-monitoring/
  • GitHub Check: packages/vendure-plugin-shipping-extensions/
  • GitHub Check: packages/vendure-plugin-shipmate/
  • GitHub Check: packages/vendure-plugin-sendcloud/
  • GitHub Check: packages/vendure-plugin-public-customer-groups/
  • GitHub Check: packages/vendure-plugin-primary-collection/
  • GitHub Check: packages/vendure-plugin-popularity-scores/
  • GitHub Check: packages/vendure-plugin-picqer/
  • GitHub Check: packages/vendure-plugin-picklist/
  • GitHub Check: packages/vendure-plugin-myparcel/
  • GitHub Check: packages/vendure-plugin-multiserver-db-sessioncache/
  • GitHub Check: packages/vendure-plugin-modify-customer-orders/
  • GitHub Check: packages/vendure-plugin-coinbase/
  • GitHub Check: packages/vendure-plugin-anonymized-order/
  • GitHub Check: packages/vendure-plugin-admin-ui-helpers/
  • GitHub Check: packages/vendure-plugin-admin-social-auth/
  • GitHub Check: packages/util/
  • GitHub Check: packages/test/
  • GitHub Check: Prettier formatting

Comment on lines +647 to +649
const tenDaysFromNow = new Date();
tenDaysFromNow.setDate(tenDaysFromNow.getDate() + 10);
await adminClient.query<any, MutationUpdateAcceptBlueSubscriptionArgs>(
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix potential timezone issues with date handling

The date handling has two potential issues:

  1. Date creation doesn't consider timezone
  2. Date formatting using substring is fragile

Apply this diff to fix the issues:

-    const tenDaysFromNow = new Date();
-    tenDaysFromNow.setDate(tenDaysFromNow.getDate() + 10);
+    const tenDaysFromNow = new Date(Date.now() + 10 * 24 * 60 * 60 * 1000);
-      next_run_date: tenDaysFromNow.toISOString().substring(0, 10), // Take yyyy-mm-dd
+      next_run_date: tenDaysFromNow.toISOString().split('T')[0],

Also applies to: 669-669

@martijnvdbrug martijnvdbrug merged commit 25dfdbd into main Jan 10, 2025
41 checks passed
@martijnvdbrug martijnvdbrug deleted the feat/accept-blue-edit-subscriptions branch January 10, 2025 14:24
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.

Accept blue: add options to edit subscriptions
2 participants