Skip to content

✨️ server: add activity and push notification on card decline#622

Open
aguxez wants to merge 5 commits intomainfrom
card-declined-events
Open

✨️ server: add activity and push notification on card decline#622
aguxez wants to merge 5 commits intomainfrom
card-declined-events

Conversation

@aguxez
Copy link
Contributor

@aguxez aguxez commented Jan 7, 2026

closes #114

Summary by CodeRabbit

  • New Features

    • Push notifications for declined transactions and insufficient-funds events.
    • Activity feed now records declined transactions and "requested" actions with status, reason, timestamps, merchant/icon, and transaction details.
    • User-facing handling for frozen or non-active cards with clear responses.
  • Bug Fixes

    • Fixed a key typo.
  • Tests

    • Added/updated tests for declined-transaction flows, push notifications, and activity serialization.
  • Chores

    • Version/changeset updates.

Open with Devin

@changeset-bot
Copy link

changeset-bot bot commented Jan 7, 2026

🦋 Changeset detected

Latest commit: 0b0e25b

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@exactly/server Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link

coderabbitai bot commented Jan 7, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds server-side decline handling: classifies decline reasons, persists declined transaction bodies, routes frozen/non-active/error flows through new decline handlers, triggers push notifications for select decline types, extends activity schema to include "requested"/declined fields, and adds tests for declines and notifications.

Changes

Cohort / File(s) Summary
Changesets
.changeset/honest-peas-stand.md, .changeset/six-dancers-hang.md
Add two changeset files bumping @exactly/server (patch); metadata only.
Decline Handling Core
server/hooks/panda.ts
Add DECLINE_REASONS and NOTIFICATION_TRIGGERING_REASONS; new helpers (getDeclineReason, handleDeclinedTransaction, updateTransactionRecord, sendDeclinedNotification, handleRejectedTransaction*); integrate decline flow for requested/created/error paths; persist declined bodies; handle frozen/non-active card flows and route errors through decline handlers.
Activity Schema & Transform
server/api/activity.ts
Extend PandaActivity bodies to accept requested, optional status/reason, nested body.spend with enrichedMerchantIcon; normalize "requested" to "created"; propagate merchant icon and single timestamp; add declined-path shaping. CardActivity action set now includes requested.
Decline & Notification Tests
server/test/hooks/panda.test.ts
Add OneSignal import and push-notification tests; replace balance checks with maxWithdraw; safer transaction receipt handling; insert declined-transaction fixtures and assert appended bodies and pushes.
Activity Tests
server/test/api/activity.test.ts
Add httpSerialize/removeUndefined helpers; refactor logs/borrows gathering; adjust test payload shapes and assertions to use serialized comparisons.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CardSystem as Card System
    participant PandaHook as Panda Hook
    participant DB as Database
    participant Notif as Notification Service

    Client->>CardSystem: submit transaction
    CardSystem->>PandaHook: webhook / payload
    PandaHook->>DB: fetch card & transaction
    alt card FROZEN or not ACTIVE
        DB-->>PandaHook: card status != ACTIVE
        PandaHook->>PandaHook: getDeclineReason()
        PandaHook->>PandaHook: handleRejectedTransactionSync()
        PandaHook-->>CardSystem: 403 / decline response
    else processing error or explicit decline
        PandaHook->>PandaHook: getDeclineReason()
        PandaHook->>DB: updateTransactionRecord(...) with declined body
        DB-->>PandaHook: OK
        PandaHook->>PandaHook: handleDeclinedTransaction()
        PandaHook->>Notif: sendDeclinedNotification()
        Notif-->>Client: push notification delivered
    else success
        PandaHook-->>CardSystem: success response
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • nfmelendez
  • cruzdanilo
  • franm91
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the main changes: adding activity tracking and push notification functionality for card decline events.
Linked Issues check ✅ Passed The PR addresses both objectives from issue #114: storing activity records on card decline and sending push notifications on specific decline reasons.
Out of Scope Changes check ✅ Passed All changes are within scope: core decline handling in panda.ts, activity API expansion in activity.ts, and corresponding tests. Two changeset files document the changes appropriately.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch card-declined-events

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link

Summary of Changes

Hello @aguxez, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the server's transaction handling by introducing a mechanism to process declined card transactions. The immediate user-facing change is the implementation of push notifications, which will inform users instantly about rejected purchases. Although the foundational code for recording these declined transactions as user activity has been added, this specific database logging functionality is temporarily disabled, pending the development of corresponding user interface elements.

Highlights

  • New Transaction Handling: Implemented a new handleDeclinedTransaction function to process card rejections within the panda hook.
  • Push Notifications for Declines: Enabled push notifications for users when their card transactions are declined, providing immediate feedback on rejected purchases.
  • Deferred Activity Logging: Prepared the server-side logic for logging declined transactions as activity in the database, though this feature is currently commented out and awaiting UI implementation.
  • Test Coverage for Future Features: Added it.todo test cases to cover the future enablement of declined transaction activity logging, ensuring proper functionality once the UI is ready.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

gemini-code-assist[bot]

This comment was marked as resolved.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In @server/hooks/panda.ts:
- Around line 955-998: Remove the large commented-out DB logic inside
handleDeclinedTransaction and track the work in your issue tracker: create an
issue describing the pending UI changes needed to handle declined transactions
and include its ID; then replace the commented block with a single-line comment
in handleDeclinedTransaction referencing that issue (e.g., "See ISSUE-1234:
enable declined-transaction persistence once UI supports it"). Ensure the rest
of the function (push notification and error capture) remains unchanged.
- Line 965: Replace the existing comment "// TODO: Enable once UI has proper
designs to handle declined transactions in activity" with the coding-guideline
compliant format: use uppercase tag, a single space, and a fully lowercase
comment body (e.g. "// TODO enable once ui has proper designs to handle declined
transactions in activity"); update the line containing that TODO comment in the
server/hooks/panda.ts hook to remove the colon and capitalize only the TODO tag.
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0860357 and 118a340.

📒 Files selected for processing (3)
  • .changeset/honest-peas-stand.md
  • server/hooks/panda.ts
  • server/test/hooks/panda.test.ts
🧰 Additional context used
📓 Path-based instructions (7)
**/.changeset/*.md

📄 CodeRabbit inference engine (.cursor/rules/style.mdc)

Use a lowercase sentence in the imperative present tense for changeset summaries

Files:

  • .changeset/honest-peas-stand.md
server/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/server.mdc)

server/**/*.ts: Use c.var object to pass strongly-typed data between Hono middleware and route handlers; do not use c.set
All request validation (headers, body, params) must be handled by @hono/valibot-validator middleware; do not perform manual validation inside route handlers
Use Hono's built-in error handling by throwing new HTTPException() for expected errors; unhandled errors will be caught and logged automatically
Enforce Node.js best practices using ESLint plugin:n/recommended configuration
Enforce Drizzle ORM best practices using ESLint plugin:drizzle/all configuration, including requiring where clauses for update and delete operations
Use Drizzle ORM query builder for all database interactions; do not write raw SQL queries unless absolutely unavoidable
All authentication and authorization logic must be implemented in Hono middleware
Do not access process.env directly in application code; load all configuration and secrets once at startup and pass them through dependency injection or context
Avoid long-running, synchronous operations; use async/await correctly and be mindful of CPU-intensive tasks to prevent blocking the event loop

Files:

  • server/hooks/panda.ts
  • server/test/hooks/panda.test.ts
**/*.{js,ts,tsx,jsx,sol}

📄 CodeRabbit inference engine (AGENTS.md)

Follow linter/formatter (eslint, prettier, solhint) strictly with high strictness level. No any type.

Files:

  • server/hooks/panda.ts
  • server/test/hooks/panda.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Omit redundant type names in variable declarations - let the type system explain itself

**/*.{ts,tsx}: Use PascalCase for TypeScript types and interfaces
Use valibot for all runtime validation of API inputs, environment variables, and other data; define schemas once and reuse them
Infer TypeScript types from valibot schemas using type User = v.Input<typeof UserSchema> instead of manually defining interfaces

Files:

  • server/hooks/panda.ts
  • server/test/hooks/panda.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Omit contextual names - don't repeat class/module names in members
Omit meaningless words like 'data', 'state', 'manager', 'engine', 'value' from variable and function names unless they add disambiguation

**/*.{ts,tsx,js,jsx}: Prefer function declarations for all multi-line functions; use function expressions or arrow functions only for single-line implementations
Prefer const for all variable declarations by default; only use let if the variable's value will be reassigned
Declare each variable on its own line with its own const or let keyword, not multiple declarations on one line
Use camelCase for TypeScript variables and functions
Always use import type { ... } for type imports
Use relative paths for all imports within the project; avoid tsconfig path aliases
Follow eslint-plugin-import order: react, external libraries, then relative paths
Use object and array destructuring to access and use properties
Use object method shorthand syntax when a function is a property of an object
Prefer optional chaining (?.), nullish coalescing (??), object and array spreading (...), and for...of loops over traditional syntax
Do not use abbreviations or cryptic names; write out full words like error, parameters, request instead of err, params, req
Use Number.parseInt() instead of the global parseInt() function when parsing numbers
All classes called with new must use PascalCase
Use Buffer.from(), Buffer.alloc(), or Buffer.allocUnsafe() instead of the deprecated new Buffer()
Use @ts-expect-error instead of @ts-ignore; follow it immediately with a single-line lowercase comment explaining why the error is expected, without separators like - or :
Do not include the type in a variable's name; let the static type system do its job (e.g., use const user: User not const userObject: User)
Do not repeat the name of a class or module within its members; omit contextual names (e.g., use `class User { getProfil...

Files:

  • server/hooks/panda.ts
  • server/test/hooks/panda.test.ts
server/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

server/**/*.{ts,tsx}: Server API: implement schema-first approach using OpenAPI via hono with validation via valibot middleware
Server database: drizzle schema is source of truth. Migrations required. No direct database access in handlers - use c.var.db

Files:

  • server/hooks/panda.ts
  • server/test/hooks/panda.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/style.mdc)

For files with a single default export, name the file identically to the export; for files with multiple exports, use camelCase with a strong preference for a single word

Files:

  • server/hooks/panda.ts
  • server/test/hooks/panda.test.ts
🧠 Learnings (2)
📚 Learning: 2025-12-31T00:23:55.034Z
Learnt from: cruzdanilo
Repo: exactly/exa PR: 610
File: .changeset/ready-experts-fly.md:1-2
Timestamp: 2025-12-31T00:23:55.034Z
Learning: In the exactly/exa repository, allow and require empty changeset files (containing only --- separators) when changes are not user-facing and do not warrant a version bump. This is needed because CI runs changeset status --since origin/main and requires a changeset file to exist. Ensure such empty changesets are used only for non-user-facing changes and document the rationale in the commit or changelog notes.

Applied to files:

  • .changeset/honest-peas-stand.md
📚 Learning: 2025-12-23T19:58:16.574Z
Learnt from: CR
Repo: exactly/exa PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-23T19:58:16.574Z
Learning: Zero config local dev environment: no `.env` files, mock all external services

Applied to files:

  • server/test/hooks/panda.test.ts
🧬 Code graph analysis (2)
server/hooks/panda.ts (1)
server/utils/onesignal.ts (1)
  • sendPushNotification (7-25)
server/test/hooks/panda.test.ts (1)
server/database/schema.ts (1)
  • transactions (36-43)
🔇 Additional comments (5)
server/test/hooks/panda.test.ts (2)

2-2: LGTM!

Import adjustments for mocks are clean and improve organization.

Also applies to: 7-7


1352-1439: Test stubs properly scaffolded for future implementation.

The two test cases for declined transaction handling are well-structured and align with the commented-out database logic in server/hooks/panda.ts. Using it.todo is appropriate while waiting for UI designs.

server/hooks/panda.ts (2)

533-533: LGTM!

The call to handleDeclinedTransaction is correctly placed after the mutex is released, and the type cast is necessary due to TypeScript's union type handling.


988-998: LGTM!

Push notification implementation properly formats the transaction details and includes error handling consistent with the rest of the codebase.

.changeset/honest-peas-stand.md (1)

1-5: LGTM!

Changeset properly documents the feature addition with appropriate version bump and clear description.

@aguxez aguxez force-pushed the card-declined-events branch from 118a340 to dc0ac8a Compare January 7, 2026 18:15
@sentry
Copy link

sentry bot commented Jan 7, 2026

Codecov Report

❌ Patch coverage is 65.00000% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.38%. Comparing base (6b15e0a) to head (0b0e25b).
⚠️ Report is 2 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
server/hooks/panda.ts 63.26% 12 Missing and 6 partials ⚠️
server/api/activity.ts 72.72% 0 Missing and 3 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #622      +/-   ##
==========================================
+ Coverage   69.11%   69.38%   +0.26%     
==========================================
  Files         208      208              
  Lines        7155     7159       +4     
  Branches     2269     2267       -2     
==========================================
+ Hits         4945     4967      +22     
+ Misses       2020     2002      -18     
  Partials      190      190              
Flag Coverage Δ
e2e 52.26% <5.00%> (-16.46%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

coderabbitai[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch 3 times, most recently from 2b6c4a8 to 64325f3 Compare January 12, 2026 14:37
sentry[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch from 64325f3 to b3814d0 Compare January 13, 2026 11:09
coderabbitai[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch from b3814d0 to 8c11c8c Compare January 13, 2026 14:49
coderabbitai[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch from 8c11c8c to 77c26c2 Compare January 14, 2026 13:30
coderabbitai[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch 2 times, most recently from 98e690f to a16d92d Compare January 15, 2026 22:41
@aguxez aguxez force-pushed the card-declined-events branch from a16d92d to 685fbf3 Compare January 19, 2026 12:04
coderabbitai[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch from 685fbf3 to 4bcf82f Compare January 19, 2026 17:03
coderabbitai[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch from 4bcf82f to bbacd86 Compare January 22, 2026 14:15
Copy link

@devin-ai-integration devin-ai-integration bot left a comment

Choose a reason for hiding this comment

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

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no potential bugs to report.

View in Devin Review to see 4 additional flags.

Open in Devin Review

sentry[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch 5 times, most recently from 4ee1569 to e91e988 Compare February 16, 2026 16:55
devin-ai-integration[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch 2 times, most recently from 280933f to 517e2cc Compare February 16, 2026 21:39
devin-ai-integration[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch from 517e2cc to 2a6fdab Compare February 17, 2026 00:19
Copy link

@devin-ai-integration devin-ai-integration bot left a comment

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

View 21 additional findings in Devin Review.

Open in Devin Review

Comment on lines +1155 to +1157
const { spend } = payload.body;
const transactionId = payload.body.id ?? payload.id;
return { transactionId, spend };

Choose a reason for hiding this comment

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

🟡 Duplicate declined records and notifications when body.id is undefined for "requested" action

When the "requested" webhook has body.id as undefined (allowed by the schema at server/hooks/panda.ts:148), the validateTransactionId fallback uses payload.id (the webhook event ID) as the transaction primary key. Later, the "created" declined webhook arrives with body.id set to the actual transaction ID — a different key. Both rejectTx invocations insert separate records with isNewRecord = true, causing a duplicate push notification and two declined activity entries in the user's feed.

Detailed trace of the duplicate flow
  1. "requested" fails (e.g. InsufficientAccountLiquidity at line 424) → rejectTx called fire-and-forget at line 462 with payload.body.id = undefined.
  2. validateTransactionId at server/hooks/panda.ts:1156 returns transactionId = payload.id (e.g. "abcdef-123456").
  3. updateTransactionRecord INSERTs a row with id = "abcdef-123456", isNewRecord = true → notification sent.
  4. "created" declined webhook arrives with body.id = "31eaa81e-..." (actual tx ID).
  5. handleDeclinedTransactionrejectTxvalidateTransactionId returns transactionId = "31eaa81e-..." (different key).
  6. updateTransactionRecord INSERTs another row with id = "31eaa81e-...", isNewRecord = true → second notification sent.

The xmax = 0 guard at server/hooks/panda.ts:1121 only prevents duplicates for the same primary key. With two different keys, both upserts are treated as new records.

Impact: The user receives two push notifications for a single decline event, and the activity feed shows two duplicate declined entries.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@aguxez aguxez force-pushed the card-declined-events branch from 2a6fdab to 914e2c0 Compare February 17, 2026 10:10
sentry[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch from 914e2c0 to d907571 Compare February 17, 2026 22:35
Copy link

@devin-ai-integration devin-ai-integration bot left a comment

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

View 23 additional findings in Devin Review.

Open in Devin Review

Comment on lines +1309 to +1318
} catch (error: unknown) {
captureException(error, { level: "error" });
return;
}

if (isNewRecord && NOTIFICATION_TRIGGERING_REASONS.has(reason)) {
await sendDeclinedNotification(account, spend, reason).catch((error: unknown) => {
captureException(error, { level: "error" });
});
}

Choose a reason for hiding this comment

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

🚩 Notification suppressed for existing transaction records regardless of reason change

The notification logic at server/hooks/panda.ts:1314 sends notifications only when isNewRecord && NOTIFICATION_TRIGGERING_REASONS.has(reason). This means if a transaction record already exists (e.g., from a prior rejectTx call during the "requested" phase with a non-triggering reason like "transaction declined"), a subsequent decline event with a triggering reason (e.g., "insufficient funds") will NOT send a notification because isNewRecord is false.

Scenario: (1) "requested" fails with "bad collection" → rejectTx inserts record, reason maps to "transaction declined" (not in triggering set), no notification. (2) "created" arrives with status "declined" and declinedReason="insufficient_funds" → rejectTx updates existing record, isNewRecord=false → no notification despite the reason being triggering.

In practice this edge case may be rare (most InsufficientAccountLiquidity errors would trigger notifications in step 1), but it's a design limitation worth understanding.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@aguxez aguxez force-pushed the card-declined-events branch from d907571 to b2de9c4 Compare February 19, 2026 14:01
@aguxez aguxez force-pushed the card-declined-events branch from b2de9c4 to abf0b03 Compare February 19, 2026 16:07
@greptile-apps
Copy link

greptile-apps bot commented Feb 19, 2026

Greptile Summary

adds comprehensive support for declined card transactions with activity tracking and push notifications. the implementation handles three decline scenarios: frozen cards (checked upfront on requested action), insufficient funds/merchant blocks (via rejectTx on authorization errors), and network declines (via handleDeclinedTransaction on created/updated with declined status).

key changes:

  • server/hooks/panda.ts: added frozen card validation, rejectTx function for recording declined transactions with upsert logic (xmax = 0 check for deduplication), push notifications for insufficient funds/frozen/merchant blocked reasons only
  • server/api/activity.ts: enhanced PandaActivity schema to parse declined transactions with status: "declined" and reason fields, normalizes requestedcreated action, uses flatten for better error context
  • replaced balanceOf + convertToAssets with direct maxWithdraw call (more accurate and efficient)
  • comprehensive test coverage for declined flows, notification deduplication, and interleaved transaction states

the implementation correctly prevents duplicate notifications using postgres xmax = 0 to detect new inserts vs updates.

Confidence Score: 4/5

  • safe to merge with comprehensive test coverage and proper error handling
  • well-tested implementation with thorough edge case coverage (frozen cards, concurrent transactions, notification deduplication). the logic correctly handles declined transactions across multiple webhook actions. all changes follow established patterns and maintain backward compatibility
  • no files require special attention - the implementation is well-structured with appropriate error handling and comprehensive tests

Important Files Changed

Filename Overview
server/hooks/panda.ts added frozen card handling, declined transaction tracking with push notifications, and database upsert logic for declined transactions
server/api/activity.ts enhanced activity parsing to support declined transactions with status, reason, and merchant details; improved error context
server/test/hooks/panda.test.ts comprehensive tests for declined transactions, push notifications, and database operations; replaced balanceOf/convertToAssets with maxWithdraw
server/test/api/activity.test.ts added tests for declined transaction parsing and improved test utilities with httpSerialize helper

Sequence Diagram

sequenceDiagram
    participant Client as Card Processor
    participant Panda as Panda Webhook
    participant DB as Database
    participant Push as Push Notification
    participant Activity as Activity API

    Client->>Panda: POST /hooks/panda (transaction requested)
    alt Card FROZEN
        Panda->>DB: rejectTx (insert/update with declined)
        Panda->>Push: sendPushNotification (frozen card)
        Panda-->>Client: 403 frozen card
    else Card ACTIVE
        Panda->>Panda: authorize transaction
        Panda-->>Client: 200 ok
    end

    Client->>Panda: POST /hooks/panda (transaction declined)
    Panda->>DB: handleDeclinedTransaction
    Panda->>DB: updateTransactionRecord (upsert)
    alt isNewRecord && triggering reason
        Panda->>Push: sendDeclinedNotification
    end
    Panda-->>Client: 200 ok

    Client->>Activity: GET /activity
    Activity->>DB: query transactions
    DB-->>Activity: transaction payloads
    Activity->>Activity: parse PandaActivity
    alt declined transaction found
        Activity-->>Client: declined activity with reason
    else normal transaction
        Activity-->>Client: normal activity
    end
Loading

Last reviewed commit: abf0b03

sentry[bot]

This comment was marked as resolved.

@aguxez aguxez force-pushed the card-declined-events branch from abf0b03 to 0b0e25b Compare February 19, 2026 16:21
@greptile-apps
Copy link

greptile-apps bot commented Feb 19, 2026

Greptile Summary

adds comprehensive declined transaction tracking with push notifications and activity feed integration.

  • declined transactions now create activity feed entries with status, reason, merchant details, and timestamp
  • push notifications sent for insufficient funds, frozen card, and merchant blocked scenarios (deduped using xmax = 0 check)
  • frozen card status now explicitly handled in requested action with immediate rejection
  • error context in sentry improved by using flatten() for validation issues
  • balance checks refactored from balanceOf/convertToAssets to maxWithdraw for accuracy
  • requested action normalized to created in activity parsing
  • comprehensive test coverage for declined flows, notifications, and concurrent handling

Confidence Score: 4/5

  • safe to merge with minor style improvement recommended
  • implementation is solid with comprehensive test coverage and proper error handling. one minor style issue with field ordering in merchant object (not critical). logic correctly handles frozen cards, declined transactions, push notifications with deduplication, and activity feed integration. tests validate all edge cases including concurrency.
  • pay close attention to server/api/activity.ts:516-517 for the field ordering style issue

Important Files Changed

Filename Overview
server/api/activity.ts adds declined transaction parsing to activity feed with status, reason, and merchant details; improves error context using flatten
server/hooks/panda.ts adds comprehensive declined transaction handling with push notifications, frozen card checks, and database updates; uses maxWithdraw for balance checks
server/test/hooks/panda.test.ts adds comprehensive tests for declined transactions, push notifications, and concurrent handling; updates balance checks to use maxWithdraw

Sequence Diagram

sequenceDiagram
    participant User
    participant Panda as Panda Webhook
    participant Hook as panda.ts Hook
    participant DB as Database
    participant OneSignal as Push Notification

    User->>Panda: Card Transaction Request
    Panda->>Hook: POST /hooks/panda (action: requested)
    
    alt Card Status Check
        Hook->>DB: Query card status
        alt Card is FROZEN
            Hook->>DB: Insert declined tx (frozen_card)
            Hook->>OneSignal: Send notification (frozen card)
            Hook-->>Panda: 403 frozen card
        else Card is not ACTIVE
            Hook-->>Panda: 403 card not active
        end
    end
    
    alt Transaction Processing
        Hook->>Hook: Assess risk & validate
        Hook->>Hook: Execute onchain transaction
        alt Transaction Fails (InsufficientAccountLiquidity)
            Hook->>DB: Insert declined tx (insufficient funds)
            Hook->>OneSignal: Send notification (insufficient funds)
            Hook-->>Panda: 557 error
        else Transaction Succeeds
            Hook->>DB: Insert successful tx
            Hook-->>Panda: 200 OK
        end
    end
    
    alt Declined Transaction Webhook
        Panda->>Hook: POST /hooks/panda (action: created/updated, status: declined)
        Hook->>DB: Query card & account
        Hook->>DB: Upsert declined tx record
        alt First declined event for this tx
            Hook->>OneSignal: Send notification
        end
        Hook-->>Panda: 200 OK
    end
    
    User->>Hook: GET /api/activity
    Hook->>DB: Query transactions
    Hook->>Hook: Parse PandaActivity (declined status)
    Hook-->>User: Activity feed with declined tx
Loading

Last reviewed commit: 0b0e25b

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

9 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment on lines 516 to +517
state: "",
icon: activity.body.spend.enrichedMerchantIcon,
Copy link

Choose a reason for hiding this comment

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

field order changed from icon, state to state, icon - keep original field ordering to minimize diff noise

Suggested change
state: "",
icon: activity.body.spend.enrichedMerchantIcon,
icon: activity.body.spend.enrichedMerchantIcon,
state: "",

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link

@devin-ai-integration devin-ai-integration bot left a comment

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

View 24 additional findings in Devin Review.

Open in Devin Review

Choose a reason for hiding this comment

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

🚩 Pre-existing field name mismatch: timestamps vs timestamp in activity endpoint

The PandaActivity schema at server/api/activity.ts:335 defines the borrows field as array(nullable(object({ timestamp: optional(bigint()), events: array(Borrow) }))) — note timestamp (singular). However, the activity endpoint at server/api/activity.ts:262 constructs borrow objects with timestamps (plural):

return {
  events: b.events,
  timestamps: b.blockNumber && timestamps.get(b.blockNumber),
};

Because valibot's object() strips unknown keys, the timestamps property is silently dropped during parsing, and timestamp is always undefined. This means borrow?.timestamp at line 383 is always undefined, causing blockTimestamp to always fall back to BigInt(Math.floor(new Date(createdAt).getTime() / 1000)) in CreditActivity and InstallmentsActivity. This is pre-existing (not introduced by this PR), but it means borrow rate calculations for panda activities use the less accurate createdAt-derived timestamp instead of the actual block timestamp. The PR's test change at server/test/api/activity.test.ts:183 correctly uses timestamp (singular), so tests pass — but they don't exercise the production code path that constructs the borrow data in the endpoint handler.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

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.

server: handle card declined events

2 participants