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/soft-trains-dig.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@exactly/server": patch
---

✨ support multiple cards in statement
108 changes: 58 additions & 50 deletions server/api/activity.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { renderToBuffer } from "@react-pdf/renderer";

import { captureException, setUser } from "@sentry/node";
import { and, arrayOverlaps, eq, inArray } from "drizzle-orm";
import { arrayOverlaps, eq } from "drizzle-orm";
import { Hono } from "hono";
import { accepts } from "hono/accepts";
import { validator as vValidator } from "hono-openapi/valibot";
Expand Down Expand Up @@ -90,7 +90,7 @@ export default new Hono().get(
columns: { account: true },
with: {
cards: {
columns: {},
columns: { id: true, lastFour: true },
with: { transactions: { columns: { hashes: true, payload: true } } },
limit: ignore("card") || maturity !== undefined ? 0 : undefined,
},
Expand Down Expand Up @@ -262,29 +262,27 @@ export default new Hono().get(
].map((blockNumber) => publicClient.getBlock({ blockNumber })),
);
const timestamps = new Map(blocks.map(({ number: block, timestamp }) => [block, timestamp]));
let statementCards: string[] = [];
let cardPurchases: typeof credential.cards;
if (!ignore("card") && maturity !== undefined && borrows) {
const hashes = borrows
.entries()
.filter(([_, { events }]) => events.some(({ maturity: m }) => Number(m) === maturity))
.map(([hash]) => hash)
.toArray();
const userCards = await database.query.cards
.findMany({ columns: { id: true }, where: eq(cards.credentialId, credentialId) })
.then((rows) => rows.map(({ id }) => id));
const statementTransactions =
hashes.length === 0 || userCards.length === 0
? []
: await database.query.transactions.findMany({
where: and(arrayOverlaps(transactions.hashes, hashes), inArray(transactions.cardId, userCards)),
columns: { cardId: true, hashes: true, payload: true },
const purchases =
!ignore("card") && borrows && maturity !== undefined
? await (() => {
const hashes = borrows
.entries()
.filter(([_, { events }]) => events.some(({ maturity: m }) => Number(m) === maturity))
.map(([hash]) => hash)
.toArray();
if (hashes.length === 0) return [];
return database.query.cards.findMany({
where: eq(cards.credentialId, credentialId),
columns: { id: true, lastFour: true },
with: {
transactions: {
columns: { hashes: true, payload: true },
where: arrayOverlaps(transactions.hashes, hashes),
},
},
});
statementCards = [...new Set(statementTransactions.map(({ cardId }) => cardId))];
cardPurchases = [{ transactions: statementTransactions }];
} else {
cardPurchases = credential.cards;
}
})()
: credential.cards;

const accept = accepts(c, {
header: "Accept",
Expand All @@ -294,7 +292,7 @@ export default new Hono().get(
const pdf = accept === "application/pdf";

const response = [
...cardPurchases.flatMap(({ transactions: txs }) =>
...purchases.flatMap(({ transactions: txs }) =>
txs.map(({ hashes, payload }) => {
const panda = safeParse(PandaActivity, {
...(payload as object),
Expand Down Expand Up @@ -423,20 +421,16 @@ export default new Hono().get(
.toSorted((a, b) => b.timestamp.localeCompare(a.timestamp) || b.id.localeCompare(a.id));

if (maturity !== undefined && pdf) {
if (statementCards.length > 1) return c.json({ code: "multiple cards" }, 400);
const statementCurrency = market(marketUSDCAddress).symbol;
const card =
statementCards.length === 0
? undefined
: await database.query.cards.findFirst({
columns: { lastFour: true },
where: and(eq(cards.credentialId, credentialId), inArray(cards.id, statementCards)),
});
const statement = {
maturity,
lastFour: card?.lastFour ?? "",
data: response.flatMap((item): Parameters<typeof Statement>[0]["data"] => {
const cardLookup = new Map(
purchases.flatMap(({ id, transactions: txs }) =>
txs.flatMap(({ hashes }) => hashes.map((hash) => [hash, id] as const)),
),
);
const purchasesByCard = Map.groupBy(
response.flatMap((item) => {
if (item.type === "panda") {
const cardId = item.operations[0] && cardLookup.get(item.operations[0].transactionHash);
if (!cardId) return [];
const installments = item.operations
.reduce((accumulator, operation) => {
if ("borrow" in operation) {
Expand Down Expand Up @@ -470,6 +464,7 @@ export default new Hono().get(
if (installments.length === 0) return [];
return [
{
cardId,
id: item.id,
timestamp: item.timestamp,
description: `${item.merchant.name}${item.merchant.city ? `, ${item.merchant.city}` : ""}`,
Expand All @@ -478,6 +473,8 @@ export default new Hono().get(
];
}
if (item.type === "card" && "borrow" in item) {
const cardId = cardLookup.get(item.transactionHash);
if (!cardId) return [];
if ("installments" in item.borrow) {
const events = borrows?.get(item.transactionHash)?.events;
if (!events) return [];
Expand All @@ -490,6 +487,7 @@ export default new Hono().get(
if (installments.length === 0) return [];
return [
{
cardId,
id: item.id,
timestamp: item.timestamp,
description: `${item.merchant.name}${item.merchant.city ? `, ${item.merchant.city}` : ""}`,
Expand All @@ -501,27 +499,37 @@ export default new Hono().get(
if (!borrow || Number(borrow.maturity) !== maturity) return [];
return [
{
cardId,
id: item.id,
timestamp: item.timestamp,
description: `${item.merchant.name}${item.merchant.city ? `, ${item.merchant.city}` : ""}`,
installments: [{ amount: Number(borrow.assets + borrow.fee) / 1e6, current: 1, total: 1 }],
},
];
}
if (item.type === "repay") {
if (item.currency !== statementCurrency) return [];
return [
{
id: item.id,
timestamp: item.timestamp,
currency: item.currency,
positionAmount: item.positionAmount,
amount: item.amount,
},
];
}
return [];
}),
({ cardId }) => cardId,
);
const statement = {
account: `${account.slice(0, 6)}...${account.slice(-6)}`,
maturity,
cards: purchases
.filter(({ id }) => purchasesByCard.has(id))
.map(({ id, lastFour }) => ({
id,
lastFour,
purchases: (purchasesByCard.get(id) ?? []).map(({ cardId: _, ...rest }) => rest),
})),
payments: response
.filter((item) => item.type === "repay")
.filter((repay) => repay.currency === market(marketUSDCAddress).symbol)
.map(({ id, timestamp, amount, positionAmount }) => ({
id,
timestamp,
amount,
positionAmount,
})),
};
return c.body(new Uint8Array(await renderToBuffer(Statement(statement))), 200, {
"content-type": "application/pdf",
Expand Down
20 changes: 17 additions & 3 deletions server/test/api/activity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ describe.concurrent("authenticated", () => {
let maturity: string;

beforeAll(async () => {
await database.insert(cards).values([{ id: "activity", credentialId: "bob", lastFour: "1234" }]);
await database.insert(cards).values([
{ id: "first-activity-card", credentialId: "bob", lastFour: "1234" },
{ id: "second-activity-card", credentialId: "bob", lastFour: "6789" },
]);
const borrows = await anvilClient.getContractEvents({
abi: marketAbi,
eventName: "BorrowAtMaturity",
Expand Down Expand Up @@ -148,7 +151,7 @@ describe.concurrent("authenticated", () => {
};
return {
id: String(index),
cardId: "activity",
cardId: index === 0 ? "first-activity-card" : "second-activity-card",
hashes,
payload,
hash,
Expand Down Expand Up @@ -218,7 +221,7 @@ describe.concurrent("authenticated", () => {
it("reports bad transaction", async () => {
await database
.insert(transactions)
.values([{ id: "bad-transaction", cardId: "activity", hashes: ["0x1"], payload: {} }]);
.values([{ id: "bad-transaction", cardId: "first-activity-card", hashes: ["0x1"], payload: {} }]);
const response = await appClient.index.$get(
{ query: { include: "card" } },
{ headers: { "test-credential-id": "bob" } },
Expand Down Expand Up @@ -251,6 +254,17 @@ describe.concurrent("authenticated", () => {
expect(json.every((item) => !item.borrow || item.borrow.maturity === Number(maturity))).toBe(true);
});

it("returns empty card activity for unmatched maturity", async () => {
expect.hasAssertions();
const response = await appClient.index.$get(
{ query: { include: "card", maturity: "0" } },
{ headers: { "test-credential-id": "bob" } },
);

expect(response.status).toBe(200);
await expect(response.json()).resolves.toStrictEqual([]);
});

it("returns statement pdf", async () => {
expect.hasAssertions();
const response = await appClient.index.$get(
Expand Down
Loading
Loading