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

Added send money card and p2p transaction UI & logic #10

Open
wants to merge 2 commits into
base: migration
Choose a base branch
from
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
24 changes: 22 additions & 2 deletions apps/bank-webhook/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ app.use(express.json())
app.post("/hdfcWebhook", async (req, res) => {
//TODO: Add zod validation here?
//TODO: HDFC bank should ideally send us a secret so we know this is sent by them

const paymentInformation: {
token: string;
userId: string;
Expand All @@ -17,6 +18,25 @@ app.post("/hdfcWebhook", async (req, res) => {
amount: req.body.amount
};

// database check
const getRecord = await db.onRampTransaction.findUnique({
where: {
token: paymentInformation.token,
},
})

if (getRecord?.status == "Success") {
return res.status(409).json({
message: "Transaction already processed"
})
}

if (getRecord?.amount != Number(paymentInformation.amount)) {
return res.status(203).json({
message: "Requested amount mismatch"
})
}

try {
await db.$transaction([
db.balance.updateMany({
Expand All @@ -33,7 +53,7 @@ app.post("/hdfcWebhook", async (req, res) => {
db.onRampTransaction.updateMany({
where: {
token: paymentInformation.token
},
},
data: {
status: "Success",
}
Expand All @@ -43,7 +63,7 @@ app.post("/hdfcWebhook", async (req, res) => {
res.json({
message: "Captured"
})
} catch(e) {
} catch (e) {
console.error(e);
res.status(411).json({
message: "Error while processing webhook"
Expand Down
28 changes: 17 additions & 11 deletions apps/user-app/app/(dashboard)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,39 @@ export default function Layout({
}): JSX.Element {
return (
<div className="flex">
<div className="w-72 border-r border-slate-300 min-h-screen mr-4 pt-28">
<div>
<SidebarItem href={"/dashboard"} icon={<HomeIcon />} title="Home" />
<SidebarItem href={"/transfer"} icon={<TransferIcon />} title="Transfer" />
<SidebarItem href={"/transactions"} icon={<TransactionsIcon />} title="Transactions" />
</div>
<div className="w-72 border-r border-slate-300 min-h-screen mr-4 pt-28">
<div>
<SidebarItem href={"/dashboard"} icon={<HomeIcon />} title="Home" />
<SidebarItem href={"/transfer"} icon={<TransferIcon />} title="Transfer" />
<SidebarItem href={"/transactions"} icon={<TransactionsIcon />} title="Transactions" />
<SidebarItem href={"/p2ptransfer"} icon={<P2PTransferIcon />} title="P2P Transfer" />
</div>
{children}
</div>
{children}
</div>
);
}

// Icons Fetched from https://heroicons.com/
function HomeIcon() {
return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6">
return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" d="m2.25 12 8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25" />
</svg>
}
function TransferIcon() {
return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6">
return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M7.5 21 3 16.5m0 0L7.5 12M3 16.5h13.5m0-13.5L21 7.5m0 0L16.5 12M21 7.5H7.5" />
</svg>
}

function TransactionsIcon() {
return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6">
return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
</svg>

}

function P2PTransferIcon() {
return <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6">
<path strokeLinecap="round" strokeLinejoin="round" d="m4.5 19.5 15-15m0 0H8.25m11.25 0v11.25" />
</svg>
}
63 changes: 63 additions & 0 deletions apps/user-app/app/(dashboard)/p2ptransfer/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { getServerSession } from "next-auth";
import { SendMoney } from "../../../components/SendMoneyCard";
import { authOptions } from "../../lib/auth";
import prisma from "@repo/db/client";
import { P2PTransactions } from "../../../components/P2PTransactions";

async function getP2PTransactions() {
const session = await getServerSession(authOptions);
const txns = await prisma.p2pTransfer.findMany({
where: {
OR: [
{
fromUserId: Number(session?.user?.id)
},
{
toUserId: Number(session?.user?.id)
}
]
}
});
return txns.map(t => {
if (t.fromUserId == session?.user?.id) {
return (
{
time: new Date(t.timestamp),
amount: t.amount,
type: "DEBIT",
userId: t.toUserId,
}
)
} else if (t.toUserId == session?.user?.id) {
return (
{
time: new Date(t.timestamp),
amount: t.amount,
type: "CREDIT",
userId: t.fromUserId
}
)
}
})
}

export default async function () {

const transactions = await getP2PTransactions();

return <div className="w-screen">
<div className="text-4xl text-[#6a51a6] pt-8 mb-8 font-bold">
P2P Transfer
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 p-4">
<div>
<SendMoney />
</div>

<div className="pt-4">
<P2PTransactions transactions={transactions} />
</div>

</div>
</div>
}
34 changes: 34 additions & 0 deletions apps/user-app/app/lib/actions/createOnrampTransaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"use server";

import prisma from "@repo/db/client";
import { getServerSession } from "next-auth";
import { authOptions } from "../auth";

export async function createOnRampTransactions(amount: number, provider: string) {

const session = await getServerSession(authOptions)
const userId = session.user.id;
const token = Math.random().toString();

if (!userId) {
return {
message: "User not logged in"
}
}

await prisma.onRampTransaction.create({
data: {
userId: Number(userId),
amount: amount,
status: "Processing",
startTime: new Date(),
provider,
token
}
})

return {
message: "On ramp transaction added"
}

}
55 changes: 55 additions & 0 deletions apps/user-app/app/lib/actions/p2pTransfer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"use server"
import { getServerSession } from "next-auth";
import { authOptions } from "../auth";
import prisma from "@repo/db/client";

export async function p2pTransfer(to: string, amount: number) {
const session = await getServerSession(authOptions);
const from = session?.user?.id;
if (!from) {
return {
message: "Error while sending"
}
}
const toUser = await prisma.user.findFirst({
where: {
number: to
}
});

if (!toUser) {
return {
message: "User not found"
}
}
await prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT * FROM "Balance" WHERE "userId" = ${Number(from)} FOR UPDATE`;

const fromBalance = await tx.balance.findUnique({
where: { userId: Number(from) },
});
if (!fromBalance || fromBalance.amount < amount) {
throw new Error('Insufficient funds');
}

await tx.balance.update({
where: { userId: Number(from) },
data: { amount: { decrement: amount } },
});

await tx.balance.update({
where: { userId: toUser.id },
data: { amount: { increment: amount } },
});

await tx.p2pTransfer.create({
data: {
amount,
timestamp: new Date(),
fromUserId: Number(from),
toUserId: toUser.id,
}
})

});
}
47 changes: 26 additions & 21 deletions apps/user-app/components/AddMoneyCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Center } from "@repo/ui/center";
import { Select } from "@repo/ui/select";
import { useState } from "react";
import { TextInput } from "@repo/ui/textinput";
import { createOnRampTransactions } from "../app/lib/actions/createOnrampTransaction";

const SUPPORTED_BANKS = [{
name: "HDFC Bank",
Expand All @@ -16,27 +17,31 @@ const SUPPORTED_BANKS = [{

export const AddMoney = () => {
const [redirectUrl, setRedirectUrl] = useState(SUPPORTED_BANKS[0]?.redirectUrl);
return <Card title="Add Money">
<div className="w-full">
<TextInput label={"Amount"} placeholder={"Amount"} onChange={() => {
const [amount, setAmount] = useState(0)
const [provider, setProvider] = useState(SUPPORTED_BANKS[0]?.name || "")

}} />
<div className="py-4 text-left">
Bank
</div>
<Select onSelect={(value) => {
setRedirectUrl(SUPPORTED_BANKS.find(x => x.name === value)?.redirectUrl || "")
}} options={SUPPORTED_BANKS.map(x => ({
key: x.name,
value: x.name
}))} />
<div className="flex justify-center pt-4">
<Button onClick={() => {
window.location.href = redirectUrl || "";
}}>
Add Money
</Button>
return <Card title="Add Money">
<div className="w-full">
<TextInput label={"Amount"} placeholder={"Amount"} onChange={(value) => {
setAmount(Number(value))
}} />
<div className="py-4 text-left">
Bank
</div>
<Select onSelect={(value) => {
setRedirectUrl(SUPPORTED_BANKS.find(x => x.name === value)?.redirectUrl || "")
}} options={SUPPORTED_BANKS.map(x => ({
key: x.name,
value: x.name
}))} />
<div className="flex justify-center pt-4">
<Button onClick={async () => {
await createOnRampTransactions(amount * 100, provider)
window.location.href = redirectUrl || "";
}}>
Add Money
</Button>
</div>
</div>
</div>
</Card>
</Card>
}
44 changes: 44 additions & 0 deletions apps/user-app/components/P2PTransactions.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Card } from "@repo/ui/card"

export const P2PTransactions = ({
transactions
}: {
transactions: {
time: Date,
amount: number,
type: string,
userId: number
}[]

}) => {
if (!transactions.length) {
return <Card title="Recent Transactions">
<div className="text-center pb-8 pt-8">
No Recent transactions
</div>
</Card>
}
return <Card title="Recent Transactions">
<div className="pt-2">
{transactions.map(t => <div className="flex justify-between">
<div>
<div className="text-sm">
{t.type === "DEBIT" ? `Sent to ${t.userId}` : `Received from ${t.userId}`}
</div>

<div className="text-slate-600 text-xs">
{t.time.toDateString()}
</div>
</div>
{t.type === "DEBIT" ?
<div className="flex flex-col justify-center text-red-600">
- Rs {t.amount / 100}
</div> : <div className="flex flex-col justify-center text-green-600">
Rs {t.amount / 100}
</div>
}

</div>)}
</div>
</Card >
}
Loading