feat: added purchase stock component

This commit is contained in:
bracesproul
2025-03-06 11:10:15 -08:00
parent 06b865c1c2
commit f7c750eceb
6 changed files with 221 additions and 46 deletions

View File

@@ -4,6 +4,7 @@ import AccommodationsList from "./trip-planner/accommodations-list";
import BookAccommodation from "./trip-planner/book-accommodation";
import RestaurantsList from "./trip-planner/restaurants-list";
import BookRestaurant from "./trip-planner/book-restaurant";
import BuyStock from "./stockbroker/buy-stock";
const ComponentMap = {
"stock-price": StockPrice,
@@ -12,5 +13,6 @@ const ComponentMap = {
"book-accommodation": BookAccommodation,
"restaurants-list": RestaurantsList,
"book-restaurant": BookRestaurant,
"buy-stock": BuyStock,
} as const;
export default ComponentMap;

View File

@@ -0,0 +1 @@
@import "tailwindcss";

View File

@@ -0,0 +1,139 @@
import "./index.css";
import { v4 as uuidv4 } from "uuid";
import { Snapshot } from "../../../types";
import { Button } from "@/components/ui/button";
import { useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { UIMessage, useStreamContext } from "@langchain/langgraph-sdk/react-ui";
import { Message } from "@langchain/langgraph-sdk";
import { getToolResponse } from "agent/uis/utils/get-tool-response";
import { DO_NOT_RENDER_ID_PREFIX } from "@/lib/ensure-tool-responses";
function Purchased({
ticker,
quantity,
price,
}: {
ticker: string;
quantity: number;
price: number;
}) {
return (
<div className="w-full md:w-lg rounded-xl shadow-md overflow-hidden border border-gray-200 flex flex-col gap-4 p-3">
<h1 className="text-xl font-medium mb-2">Purchase Executed - {ticker}</h1>
<div className="grid grid-cols-2 gap-4 text-sm mb-4">
<div className="flex flex-col gap-2">
<p>Number of Shares</p>
<p>Market Price</p>
<p>Total Cost</p>
</div>
<div className="flex flex-col gap-2 items-end justify-end">
<p>{quantity}</p>
<p>${price}</p>
<p>${(quantity * price).toFixed(2)}</p>
</div>
</div>
</div>
);
}
export default function BuyStock(props: {
toolCallId: string;
snapshot: Snapshot;
quantity: number;
}) {
const { snapshot, toolCallId } = props;
const [quantity, setQuantity] = useState(props.quantity);
const [finalPurchase, setFinalPurchase] = useState<{
ticker: string;
quantity: number;
price: number;
}>();
const thread = useStreamContext<
{ messages: Message[]; ui: UIMessage[] },
{ MetaType: { ui: UIMessage | undefined } }
>();
useEffect(() => {
if (typeof window === "undefined" || finalPurchase) return;
const toolResponse = getToolResponse(toolCallId, thread);
if (toolResponse) {
try {
const parsedContent: {
purchaseDetails: {
ticker: string;
quantity: number;
price: number;
};
} = JSON.parse(toolResponse.content as string);
setFinalPurchase(parsedContent.purchaseDetails);
} catch {
console.error("Failed to parse tool response content.");
}
}
}, []);
function handleBuyStock() {
const orderDetails = {
message: "Successfully purchased stock",
purchaseDetails: {
ticker: snapshot.ticker,
quantity: quantity,
price: snapshot.price,
},
};
thread.submit({
messages: [
{
type: "tool",
tool_call_id: toolCallId,
id: `${DO_NOT_RENDER_ID_PREFIX}${uuidv4()}`,
name: "buy-stock",
content: JSON.stringify(orderDetails),
},
{
type: "human",
content: `Purchased ${quantity} shares of ${snapshot.ticker} at ${snapshot.price} per share`,
},
],
});
setFinalPurchase(orderDetails.purchaseDetails);
}
if (finalPurchase) {
return <Purchased {...finalPurchase} />;
}
return (
<div className="w-full md:w-lg rounded-xl shadow-md overflow-hidden border border-gray-200 flex flex-col gap-4 p-3">
<h1 className="text-xl font-medium mb-2">Buy {snapshot.ticker}</h1>
<div className="grid grid-cols-2 gap-4 text-sm mb-4">
<div className="flex flex-col gap-2">
<p>Number of Shares</p>
<p>Market Price</p>
<p>Total Cost</p>
</div>
<div className="flex flex-col gap-2 items-end justify-end">
<Input
type="number"
className="max-w-[100px] border-0 border-b focus:border-b-2 rounded-none shadow-none focus:ring-0"
value={quantity}
onChange={(e) => setQuantity(Number(e.target.value))}
min={1}
/>
<p>${snapshot.price}</p>
<p>${(quantity * snapshot.price).toFixed(2)}</p>
</div>
</div>
<Button
className="w-full bg-green-600 hover:bg-green-700 transition-colors ease-in-out duration-200 cursor-pointer text-white"
onClick={handleBuyStock}
>
Buy
</Button>
</div>
);
}

View File

@@ -1,9 +1,4 @@
import "./index.css";
import {
useStreamContext,
type UIMessage,
} from "@langchain/langgraph-sdk/react-ui";
import type { Message } from "@langchain/langgraph-sdk";
import { useState, useMemo } from "react";
import {
ChartConfig,
@@ -65,42 +60,26 @@ function DisplayRangeSelector({
);
}
function getPropsForDisplayRange(displayRange: DisplayRange, prices: Price[]) {
// Start by filtering prices by display range. use the `time` field on `price` which is a string date. compare it to the current date
const actualPrices: Price[] = [];
function getPropsForDisplayRange(
displayRange: DisplayRange,
oneDayPrices: Price[],
thirtyDayPrices: Price[],
) {
const now = new Date();
const oneDay = 24 * 60 * 60 * 1000;
const fiveDays = 5 * oneDay;
const oneMonth = 30 * oneDay;
const fiveDays = 5 * 24 * 60 * 60 * 1000; // 5 days in milliseconds
switch (displayRange) {
case "1d":
console.log("Calculating for 1d", prices.length);
console.log(prices[prices.length - 1]);
actualPrices.push(
...prices.filter(
(p) => new Date(p.time).getTime() >= now.getTime() - oneDay,
),
);
break;
return oneDayPrices;
case "5d":
console.log("Calculating for 5d", prices.length);
actualPrices.push(
...prices.filter(
(p) => new Date(p.time).getTime() >= now.getTime() - fiveDays,
),
return thirtyDayPrices.filter(
(p) => new Date(p.time).getTime() >= now.getTime() - fiveDays,
);
break;
case "1m":
console.log("Calculating for 1m", prices.length);
actualPrices.push(
...prices.filter(
(p) => new Date(p.time).getTime() >= now.getTime() - oneMonth,
),
);
break;
return thirtyDayPrices;
default:
return [];
}
return actualPrices;
}
// TODO: UPDATE TO SUPPORT ONE DAY AND THIRTY DAY PRICES AS DIFFERENT PROPS
export default function StockPrice(props: {
@@ -109,12 +88,8 @@ export default function StockPrice(props: {
thirtyDayPrices: Price[];
}) {
const { ticker } = props;
console.log(props.prices[0], props.prices[props.prices.length - 1]);
const { oneDayPrices, thirtyDayPrices } = props;
const [displayRange, setDisplayRange] = useState<DisplayRange>("1d");
const thread = useStreamContext<
{ messages: Message[]; ui: UIMessage[] },
{ MetaType: { ui: UIMessage | undefined } }
>();
const {
currentPrice,
@@ -126,8 +101,12 @@ export default function StockPrice(props: {
chartData,
change,
} = useMemo(() => {
const prices = getPropsForDisplayRange(displayRange, props.prices);
console.log("prices", prices.length);
const prices = getPropsForDisplayRange(
displayRange,
oneDayPrices,
thirtyDayPrices,
);
const firstPrice = prices[0];
const lastPrice = prices[prices.length - 1];
@@ -158,7 +137,7 @@ export default function StockPrice(props: {
chartData,
change,
};
}, [props.prices, displayRange]);
}, [oneDayPrices, thirtyDayPrices, displayRange]);
return (
<div className="w-full max-w-4xl rounded-xl shadow-md overflow-hidden border border-gray-200 flex flex-col gap-4 p-3">