Skip to content

feat: creating recurring payments and set up webhook for payments #83

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

Open
wants to merge 7 commits into
base: feat/19-manage-recurring-payments
Choose a base branch
from

Conversation

bassgeta
Copy link

@bassgeta bassgeta commented Jun 18, 2025

Implemented a form for users to create recurring payments via easy invoice.

Changes

Added

  • Webhook handling of payments that are part of recurring payments.
  • Create recurring payment handler with prompts for connecting the user's wallet.
  • Create recurring payment form with validation.
  • Endpoint for submitting the required signature for recurring payments to work.
  • Endpoint for creating a recurring payment.
  • Recurrence fields to the base payment schema.

Reworked

  • Decoupled payment form schemas (direct payment, batch payment and recurring payment) from their API counterparts. Now we create 2 separate schemas, one for the Easy Invoice API endpoints, one for the forms, the form one picks the API schema values to keep validation in line.
  • A recurring payment's payments now link to request scan.
  • New component for the payment secured by request network banner.

Testing

Prerequisites

  • Test it with this API branch.
  • With easy invoice running, create a new webhook on request API via OpenAPI docs or this cURL
curl --location 'http://localhost:8080/v1/webhook' \
--header 'Content-Type: application/json' \
--header 'Cookie: session_token=<YOUR_TOKEN>' \
--data '{
    "url" : "http://localhost:3000/api/webhook"
}'
  1. Go to /payouts/recurring/create and verify that it loads appkit and then shows up the form
    image
    image
  2. Disconnect your wallet and verify that you are prompted to connect it.
    image
    3.Immediately try to submit the form and verify that validation happens
    image
  3. Try to create a new recurring payment, do something like 1 FAU 2 times Daily
    image
  4. Verify that you get prompted for signing the transaction
    image
  5. Sign it and verify that you get redirected to /payouts/recurring after it's created
    image
  6. Wait for a few minutes, the first transaction should occur, draining 1 FAU from your wallet and the webhook should add the payment to the database. It should show up in the table. Clicking on View transaction should take you to request scan.
    image

Summary by CodeRabbit

  • New Features

    • Introduced support for creating and managing recurring payments, including a multi-step interface for wallet connection and payment setup.
    • Added a form with validation for setting up recurring payments, supporting frequency, start date, and total executions.
    • Implemented batch and direct payout forms with improved schema validation and reusable security notice component.
    • Added a dedicated informational message indicating payments are secured using Request Network.
  • Improvements

    • Enhanced completed payments display by conditionally showing transaction links or hashes.
    • Updated currency and recurring payment schemas for more robust validation and flexibility.
    • Added new database fields and API endpoints to support recurring payment workflows.
  • Bug Fixes

    • Ensured recurring payments are properly appended and tracked on payment confirmation events.
  • Chores

    • Refactored and reorganized components and schema imports for clarity and maintainability.

Copy link
Contributor

coderabbitai bot commented Jun 18, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes introduce full-stack support for recurring payments, including new schemas, database fields, and API procedures. A two-step React UI for creating recurring payments is added, along with form validation and wallet integration. The backend supports recurring payment creation, signature submission, and payment tracking. Batch and direct payment forms are refactored for schema consistency and a reusable security notice component is introduced.

Changes

File(s) / Path(s) Change Summary
src/app/api/webhook/route.ts Added addPaymentToRecurringPayment helper for appending payments to recurring payment records; modified "payment.confirmed" event handling to support recurring payments.
src/app/payouts/recurring/create/page.tsx Changed import path for CreateRecurringPayment to a more specific file-level import.
src/components/batch-payout.tsx, src/components/direct-payout.tsx Refactored to define and use local schemas/types for form values; replaced hardcoded security notice with <PaymentSecuredUsingRequest />.
src/components/create-recurring-payment.tsx Deleted the previous CreateRecurringPayment component (UI-only version).
src/components/create-recurring-payment/blocks/create-recurring-payment-form.tsx Added new CreateRecurringPaymentForm component implementing full recurring payment creation flow with wallet integration, form validation, transaction approval, signature submission, and user feedback.
src/components/create-recurring-payment/create-recurring-payment.tsx Added new CreateRecurringPayment component managing a two-step UI for wallet connection and recurring payment creation.
src/components/payment-secured-using-request.tsx Added new reusable PaymentSecuredUsingRequest informational component.
src/components/view-recurring-payments/blocks/completed-payments.tsx Changed logic to display either a transaction link or a short address component based on available data.
src/lib/constants/currencies.ts Added RECURRING_PAYMENT_CURRENCIES constant array and RecurringPaymentCurrency type alias.
src/lib/schemas/payment.ts Renamed and refactored schemas/types for payment and batch payment; added recurring payment fields and validation; introduced payoutSchema.
src/lib/schemas/recurring-payment.ts Added new createRecurringPaymentSchema and CreateRecurringPaymentValues type for recurring payments.
src/server/db/schema.ts Added externalPaymentId field to recurringPaymentTable schema.
src/server/routers/payment.ts Updated procedures to use new schemas; added submitRecurringSignature procedure for recurring payments.
src/server/routers/recurring-payment.ts Added createRecurringPayment mutation procedure for recurring payments.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI as CreateRecurringPayment
    participant Form as CreateRecurringPaymentForm
    participant Wallet
    participant Server
    participant DB

    User->>UI: Open recurring payment creation page
    UI->>Wallet: Check wallet connection
    alt Not connected
        UI->>User: Prompt to connect wallet
        User->>Wallet: Connect wallet
    end
    UI->>Form: Render recurring payment form

    User->>Form: Fill form and submit
    Form->>Wallet: Request transaction approval
    Wallet-->>Form: Transaction confirmed

    Form->>Wallet: Request permit signature
    Wallet-->>Form: Signature provided

    Form->>Server: Submit recurring payment data
    Server->>DB: Insert new recurring payment record
    DB-->>Server: Success
    Server-->>Form: Return new recurring payment

    Form->>Server: Submit permit signature
    Server->>DB: Update recurring payment with signature
    DB-->>Server: Success
    Server-->>Form: Confirm recurring payment setup

    Form->>User: Show success and redirect
Loading
sequenceDiagram
    participant Webhook
    participant Server
    participant DB

    Webhook->>Server: POST "payment.confirmed" event
    alt Recurring payment (recurringPayment.id present)
        Server->>DB: Find recurring payment by externalPaymentId
        DB-->>Server: Return recurring payment
        Server->>DB: Append payment to payments array, update count
        DB-->>Server: Success
    else Non-recurring payment
        Server->>DB: Update request status to "crypto_paid" or "paid"
        DB-->>Server: Success
    end
    Server-->>Webhook: Respond
Loading

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

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.

@bassgeta bassgeta force-pushed the feat/26-create-recurring-payment branch from a072029 to 229b3f2 Compare June 23, 2025 08:10
@bassgeta bassgeta changed the title feat: initial scaffolding for creating a recurring payment feat: creating recurring payments and set up webhook for payments Jun 23, 2025
@bassgeta bassgeta marked this pull request as ready for review June 23, 2025 08:11
@bassgeta
Copy link
Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

✅ 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
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: 3

🧹 Nitpick comments (6)
src/lib/constants/currencies.ts (1)

72-79: Consider reusing existing constants to avoid duplication.

The implementation is correct and follows established patterns. However, these currencies already exist in TESTNET_CURRENCIES. Consider deriving RECURRING_PAYMENT_CURRENCIES from the existing array to maintain single source of truth:

-export const RECURRING_PAYMENT_CURRENCIES = [
-  "FAU-sepolia",
-  "fUSDC-sepolia",
-  "fUSDT-sepolia",
-] as const;
+export const RECURRING_PAYMENT_CURRENCIES = [
+  TESTNET_CURRENCIES[1], // "FAU-sepolia"
+  TESTNET_CURRENCIES[2], // "fUSDC-sepolia" 
+  TESTNET_CURRENCIES[3], // "fUSDT-sepolia"
+] as const;

Or filter from TESTNET_CURRENCIES to make the relationship explicit.

src/components/payment-secured-using-request.tsx (1)

1-13: LGTM: Well-designed reusable component.

This component effectively consolidates security notices into a reusable UI element. The styling is consistent and the message is clear. Consider adding an ARIA label for better accessibility:

-<div className="p-4 bg-green-50 border border-green-200 rounded-lg mt-4">
+<div className="p-4 bg-green-50 border border-green-200 rounded-lg mt-4" role="complementary" aria-label="Security information">
src/server/routers/payment.ts (1)

75-107: Consider adding input validation for the signature format.

The new submitRecurringSignature procedure has good authentication and error handling, but consider adding validation for the permit signature format to catch malformed signatures early.

  permitSignature: z.string().min(1, "Permit signature is required"),
+ permitSignature: z.string()
+   .min(1, "Permit signature is required")
+   .regex(/^0x[0-9a-fA-F]{130}$/, "Invalid signature format"),
src/components/create-recurring-payment/blocks/create-recurring-payment-form.tsx (2)

41-48: Consider extracting schema derivation for better maintainability.

The inline schema derivation for recurringPaymentFormSchema could be moved to a separate file or constant to improve readability and reusability.

Create a new file src/lib/schemas/recurring-payment-form.ts:

import { paymentApiSchema } from "@/lib/schemas/payment";

const recurrenceFields = paymentApiSchema.shape.recurrence
  .unwrap()
  .omit({ payer: true }).shape;

export const recurringPaymentFormSchema = paymentApiSchema
  .omit({ recurrence: true, paymentCurrency: true })
  .extend(recurrenceFields);

80-174: Consider breaking down the large onSubmit function.

The onSubmit function is quite large and handles multiple concerns. Consider extracting separate functions for payment creation, transaction approval, and signature submission to improve readability and testability.

Extract functions like:

  • createPaymentAndApproval()
  • handleTransactionApproval()
  • handlePermitSigning()
src/lib/schemas/payment.ts (1)

18-35: Consider simplifying date validation logic.

The current date validation logic is complex and might have edge cases around timezone handling. Consider using a simpler approach that's more readable and timezone-safe.

- .refine(
-   (date) => {
-     const today = new Date();
-     return (
-       date.getFullYear() > today.getFullYear() ||
-       (date.getFullYear() === today.getFullYear() &&
-         (date.getMonth() > today.getMonth() ||
-           (date.getMonth() === today.getMonth() &&
-             date.getDate() >= today.getDate())))
-     );
-   },
-   {
-     message: "Start date cannot be in the past",
-   },
- )
+ .refine(
+   (date) => {
+     const today = new Date();
+     today.setHours(0, 0, 0, 0);
+     const inputDate = new Date(date);
+     inputDate.setHours(0, 0, 0, 0);
+     return inputDate >= today;
+   },
+   {
+     message: "Start date cannot be in the past",
+   },
+ )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 74e8733 and 229b3f2.

📒 Files selected for processing (15)
  • src/app/api/webhook/route.ts (3 hunks)
  • src/app/payouts/recurring/create/page.tsx (1 hunks)
  • src/components/batch-payout.tsx (2 hunks)
  • src/components/create-recurring-payment.tsx (0 hunks)
  • src/components/create-recurring-payment/blocks/create-recurring-payment-form.tsx (1 hunks)
  • src/components/create-recurring-payment/create-recurring-payment.tsx (1 hunks)
  • src/components/direct-payout.tsx (4 hunks)
  • src/components/payment-secured-using-request.tsx (1 hunks)
  • src/components/view-recurring-payments/blocks/completed-payments.tsx (2 hunks)
  • src/lib/constants/currencies.ts (1 hunks)
  • src/lib/schemas/payment.ts (2 hunks)
  • src/lib/schemas/recurring-payment.ts (1 hunks)
  • src/server/db/schema.ts (1 hunks)
  • src/server/routers/payment.ts (4 hunks)
  • src/server/routers/recurring-payment.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • src/components/create-recurring-payment.tsx
🔇 Additional comments (16)
src/server/db/schema.ts (1)

220-220: LGTM: Well-structured schema addition.

The externalPaymentId field addition follows proper Drizzle ORM patterns and supports the recurring payment integration with external payment systems. The non-nullable constraint ensures data integrity.

src/components/view-recurring-payments/blocks/completed-payments.tsx (1)

31-43: LGTM: Improved transaction display logic.

The conditional rendering appropriately handles cases where requestScanUrl might not be available. Using ShortAddress component for transaction hash display provides consistent UX and maintains the existing link behavior when scan URLs are present.

src/app/payouts/recurring/create/page.tsx (1)

1-1: ```shell
#!/bin/bash

Verify that the component file exists and that it exports CreateRecurringPayment

file="src/components/create-recurring-payment/create-recurring-payment.tsx"

if [ -f "$file" ]; then
echo "Found: $file"
rg "export (default )?(function|const|class) CreateRecurringPayment" "$file" -A3 || echo "No matching export found in $file"
else
echo "File not found: $file"
fi


</details>
<details>
<summary>src/lib/schemas/recurring-payment.ts (1)</summary>

`1-31`: **LGTM! Well-structured schema with proper validation.**

The schema design effectively flattens recurrence fields to the top level while maintaining proper validation. The use of `unwrap()` to extract nested schema fields is a clean approach for form handling.

</details>
<details>
<summary>src/components/direct-payout.tsx (2)</summary>

`47-56`: **LGTM! Clean schema refactoring approach.**

The refactoring properly creates a component-specific schema by omitting the recurrence field from the base API schema. This maintains separation of concerns while reusing validation logic.

---

`380-380`: **Good use of reusable component.**

Replacing the hardcoded security notice with the `PaymentSecuredUsingRequest` component improves maintainability and consistency across payment forms.

</details>
<details>
<summary>src/server/routers/recurring-payment.ts (1)</summary>

`22-56`: **LGTM! Proper implementation with good security practices.**

The mutation procedure follows good patterns:
- Proper authentication checks
- Input validation using the schema
- Appropriate database field mappings
- Clean error handling

The field mappings look correct, converting numbers to strings where needed for database storage.

</details>
<details>
<summary>src/components/batch-payout.tsx (2)</summary>

`66-73`: **LGTM! Appropriate batch validation schema.**

The local schema properly validates an array of payout items with sensible constraints (1-10 payments). Using the base `payoutSchema` ensures consistency with other payment forms.

---

`569-569`: **Good consistency with reusable component.**

Using the same `PaymentSecuredUsingRequest` component maintains UI consistency across all payment forms.

</details>
<details>
<summary>src/components/create-recurring-payment/create-recurring-payment.tsx (1)</summary>

`1-128`: **LGTM! Well-structured component with proper state management.**

The component follows excellent React patterns:
- Clean state management for the two-step flow
- Proper integration with wallet hooks
- Conditional rendering with good UX (loading states)
- Consistent styling with other payment components

The step indicator provides clear visual feedback to users about their progress.

</details>
<details>
<summary>src/app/api/webhook/route.ts (2)</summary>

`39-74`: **LGTM! Well-structured function with proper error handling.**

The `addPaymentToRecurringPayment` function correctly uses database transactions and handles the case where no recurring payment is found. The array spread operation ensures immutability when adding new payments.

---

`110-122`: **Good conditional logic for handling recurring payments.**

The webhook handler correctly differentiates between recurring and regular payments using the presence of `body.recurringPayment?.id`. This maintains backward compatibility while adding new functionality.

</details>
<details>
<summary>src/server/routers/payment.ts (2)</summary>

`2-2`: **Good schema naming update for consistency.**

The import changes from `*FormSchema` to `*ApiSchema` better reflect the actual usage of these schemas in API endpoints.

---

`28-28`: **Proper handling of optional recurrence field.**

Using nullish coalescing (`??`) with `undefined` ensures the field is only included when present, maintaining clean API payloads.

</details>
<details>
<summary>src/lib/schemas/payment.ts (2)</summary>

`6-6`: **Good schema naming consistency.**

The rename from `paymentFormSchema` to `paymentApiSchema` better reflects its usage in API endpoints rather than just forms.

---

`72-74`: **Good use of refinement for mutual exclusion.**

The refinement ensuring either `payouts` or `requestIds` is provided is a clean approach to handle the either/or validation requirement.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

@bassgeta bassgeta force-pushed the feat/26-create-recurring-payment branch 4 times, most recently from f597f1f to 5d5c58e Compare June 23, 2025 10:11
@bassgeta bassgeta force-pushed the feat/26-create-recurring-payment branch from 5d5c58e to 258eaea Compare June 23, 2025 10:15
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