Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/many-steaks-slide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@exactly/server": patch
---

✨ expose unknown decline reasons
27 changes: 9 additions & 18 deletions server/api/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,16 +524,17 @@ export const PandaActivity = pipe(
.map((hash, index) => {
const borrow = borrows[index];
const body = bodies[index];
const declinedReason =
body?.body.spend.declinedReason?.toLowerCase() === "webhook declined"
? (requestedReason ?? body.body.spend.declinedReason)
: body?.body.spend.declinedReason;
const provider = body?.body.spend.declinedReason === "" ? undefined : body?.body.spend.declinedReason;
const generic = (provider ?? body?.reason)?.toLowerCase() === "webhook declined";
Comment thread
aguxez marked this conversation as resolved.
const local = body?.action === "requested" && body.status === "declined";
const mapped = declineMessage(local || generic ? requestedReason : provider);
const reason = (local || generic ? (mapped ?? "transaction declined") : (mapped ?? provider)) ?? body?.reason;
const validation = safeParse(
{ 0: DebitActivity, 1: CreditActivity }[borrow?.events.length ?? 0] ?? InstallmentsActivity,
{
...body,
...(body?.status === "declined" && {
reason: declineMessage(declinedReason) ?? body.reason ?? "transaction declined",
reason: reason ?? body.reason ?? "transaction declined",
}),
forceCapture: body?.action === "completed" && !bodies.some((b) => b.action === "created"),
type,
Expand All @@ -547,19 +548,9 @@ export const PandaActivity = pipe(
})
.filter((p) => p.provider === "panda");

const declined = (function () {
const operation = operations.findLast((b) => b.action === "created" && b.status === "declined");
if (operation) {
if (operation.reason === "webhook declined") {
const requested = operations.findLast((b) => b.action === "requested");
return requested
? { ...operation, reason: requested.reason }
: { ...operation, reason: "transaction declined" };
}
return operation;
}
return operations.findLast((b) => b.action === "requested");
})();
const declined =
operations.findLast((b) => b.action === "created" && b.status === "declined") ??
operations.findLast((b) => b.action === "requested" && b.status === "declined");

const flow = operations.reduce<{
completed: (typeof operations)[number] | undefined;
Expand Down
156 changes: 82 additions & 74 deletions server/hooks/panda.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { vValidator } from "@hono/valibot-validator";
import {
captureException,
captureMessage,
getActiveSpan,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
setContext,
Expand Down Expand Up @@ -170,7 +171,7 @@ export default function hook({
if (card.status === "FROZEN") {
trackAuthorizationRejected(account, payload, card.mode, card.credential.source, "frozen-card", segment);

await reject(payload, jsonBody, "frozenCard", database);
await reject(payload, jsonBody, "frozenCard");

return c.json({ code: "frozen card", rejectionCode: "NOT_PERMITTED" }, 403 as UnofficialStatusCode);
}
Expand Down Expand Up @@ -378,7 +379,7 @@ export default function hook({
}

if (error.message !== "Replay" && error.message !== "tx reverted") {
await reject(payload, jsonBody, error.message, database);
await reject(payload, jsonBody, error.message);
}

return c.json(
Expand All @@ -396,7 +397,7 @@ export default function hook({
);
captureException(error, { level: "error", tags: { unhandled: true } });

await reject(payload, jsonBody, error instanceof Error ? error.message : "unexpected error", database);
await reject(payload, jsonBody, error instanceof Error ? error.message : "unexpected error");

return c.json({ code: "ouch", rejectionCode: "UNKNOWN" }, 569 as UnofficialStatusCode);
}
Expand Down Expand Up @@ -515,19 +516,35 @@ export default function hook({
mutex?.release();
setContext("mutex", { locked: mutex?.isLocked() });

const requestedReason =
payload.body.spend.declinedReason?.toLowerCase() === "webhook declined"
? await getRequestedDeclineReason(payload.body.id, payload.body.spend.cardId, database)
const provider = payload.body.spend.declinedReason;
const requested =
provider?.toLowerCase() === "webhook declined"
? await database.query.transactions
.findFirst({
columns: { payload: true },
where: and(
eq(transactions.id, payload.body.id),
eq(transactions.cardId, payload.body.spend.cardId),
),
})
.then((transaction) => getRequestedDeclineReason(transaction?.payload))
: undefined;
const rawDeclineReason = requestedReason ?? payload.body.spend.declinedReason;
if (
(await reject(payload, jsonBody, rawDeclineReason ?? "transaction declined", database)) &&
payload.action === "created"
) {
const raw = requested ?? provider;
const mapped = declineMessage(raw);
const accepted = await reject(payload, jsonBody, raw ?? "transaction declined");
if (accepted && payload.action === "created" && requested === undefined && raw && !mapped) {
captureMessage("unknown panda decline reason", {
level: "warning",
tags: { reason: raw },
});
}
if (accepted && payload.action === "created") {
sendDeclinedNotification(
account,
payload.body.spend,
declineMessage(rawDeclineReason) ?? "transaction declined",
requested === undefined
? (mapped ?? raw ?? "transaction declined")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat empty provider reasons as absent

When a declined created event contains declinedReason: ""—which the transaction schema accepts—raw is an empty string, so this nullish fallback passes "" to sendDeclinedNotification() instead of "transaction declined". The resulting rejection notification has a blank reason; normalize an empty provider reason to undefined, as the activity path already does, and cover this fallback. .agents/rules/server.mdL69-L73

Useful? React with 👍 / 👎.

: (mapped ?? "transaction declined"),
onesignal,
).catch((error: unknown) => captureException(error, { level: "error" }));
}
Expand Down Expand Up @@ -887,6 +904,53 @@ export default function hook({
}
},
);
async function reject(payload: v.InferOutput<typeof Transaction>, jsonBody: unknown, declineReason: string) {
const { spend } = payload.body;
const transactionId = payload.body.id ?? payload.id;

const rawBody = v.parse(v.looseObject({ body: v.looseObject({ spend: v.looseObject({}) }) }), jsonBody);
const createdAt = getCreatedAt(payload) ?? new Date().toISOString();
const declinedBody = {
...rawBody,
...(payload.action === "requested" && {
body: { ...rawBody.body, spend: { ...rawBody.body.spend, declinedReason: declineReason } },
}),
createdAt,
status: "declined",
};

return database
.insert(transactions)
.values({
id: transactionId,
cardId: spend.cardId,
hashes: [zeroHash],
payload: { bodies: [declinedBody], type: "panda" },
})
.onConflictDoUpdate({
target: transactions.id,
set: {
hashes: sql`${transactions.hashes} || ARRAY[${zeroHash}]::text[]`,
payload: sql`jsonb_set(
${transactions.payload},
'{bodies}',
COALESCE(${transactions.payload}::jsonb->'bodies', '[]'::jsonb) || ${JSON.stringify([declinedBody])}::jsonb
)`,
},
...(payload.action === "created" && {
setWhere: sql`NOT EXISTS (
SELECT 1
FROM jsonb_array_elements(COALESCE(${transactions.payload}::jsonb->'bodies', '[]'::jsonb)) AS body
WHERE body->>'id' = ${payload.id}
)`,
}),
})
.returning({ id: transactions.id })
.then((result) => result.length > 0)
.catch((error: unknown) => {
captureException(error, { level: "error" });
});
}
return { app, ready: Promise.resolve() };
}

Expand Down Expand Up @@ -1152,27 +1216,24 @@ class PandaError extends Error {
}
}

async function getRequestedDeclineReason(transactionId: string, cardId: string, database: Database) {
const transaction = await database.query.transactions.findFirst({
columns: { payload: true },
where: and(eq(transactions.id, transactionId), eq(transactions.cardId, cardId)),
});
if (!transaction) return;

function getRequestedDeclineReason(transactionPayload: unknown) {
const payload = v.safeParse(
v.object({
bodies: v.array(
v.looseObject({
action: v.string(),
body: v.looseObject({ spend: v.looseObject({ declinedReason: v.nullish(v.string()) }) }),
reason: v.optional(v.string()),
status: v.optional(v.string()),
}),
),
}),
transaction.payload,
transactionPayload,
);
if (!payload.success) return;
const requested = payload.output.bodies.findLast(({ action }) => action === "requested");
const requested = payload.output.bodies.findLast(
({ action, status }) => action === "requested" && status === "declined",
);
return requested?.body.spend.declinedReason ?? requested?.reason;
}

Expand All @@ -1192,56 +1253,3 @@ async function sendDeclinedNotification(
}),
});
}

async function reject(
payload: v.InferOutput<typeof Transaction>,
jsonBody: unknown,
declineReason: string,
database: Database,
) {
const { spend } = payload.body;
const transactionId = payload.body.id ?? payload.id;

const rawBody = v.parse(v.looseObject({ body: v.looseObject({ spend: v.looseObject({}) }) }), jsonBody);
const createdAt = getCreatedAt(payload) ?? new Date().toISOString();
const declinedBody = {
...rawBody,
...(payload.action === "requested" && {
body: { ...rawBody.body, spend: { ...rawBody.body.spend, declinedReason: declineReason } },
}),
createdAt,
status: "declined",
};

return database
.insert(transactions)
.values({
id: transactionId,
cardId: spend.cardId,
hashes: [zeroHash],
payload: { bodies: [declinedBody], type: "panda" },
})
.onConflictDoUpdate({
target: transactions.id,
set: {
hashes: sql`${transactions.hashes} || ARRAY[${zeroHash}]::text[]`,
payload: sql`jsonb_set(
${transactions.payload},
'{bodies}',
COALESCE(${transactions.payload}::jsonb->'bodies', '[]'::jsonb) || ${JSON.stringify([declinedBody])}::jsonb
)`,
},
...(payload.action === "created" && {
setWhere: sql`NOT EXISTS (
SELECT 1
FROM jsonb_array_elements(COALESCE(${transactions.payload}::jsonb->'bodies', '[]'::jsonb)) AS body
WHERE body->>'id' = ${payload.id}
)`,
}),
})
.returning({ id: transactions.id })
.then((result) => result.length > 0)
.catch((error: unknown) => {
captureException(error, { level: "error" });
});
}
Loading
Loading