|
|
@@ -9,11 +9,13 @@
|
|
|
|
|
|
let chartCanvas;
|
|
|
let chartInstance;
|
|
|
+ let selectedRange = '5d'; // default range
|
|
|
|
|
|
- const endpoint = `https://stocks-be.lhamacorp.com/api/stocks/${code}/history`;
|
|
|
+ const ranges = ['5d', '30d', '6m', '1y'];
|
|
|
|
|
|
- async function fetchData() {
|
|
|
+ async function fetchData(range) {
|
|
|
try {
|
|
|
+ const endpoint = `https://stocks-be.lhamacorp.com/api/stocks/${code}/history?range=${range}`;
|
|
|
const res = await getRequest(endpoint, {}, null);
|
|
|
if (!res.ok) {
|
|
|
console.error(`Failed to fetch price history: ${res.status}`);
|
|
|
@@ -27,7 +29,13 @@
|
|
|
}
|
|
|
|
|
|
function renderChart(data) {
|
|
|
- const labels = data.map((item) => new Date(item.createdAt).toLocaleDateString());
|
|
|
+ const labels = data.map((item) => {
|
|
|
+ const date = new Date(item.createdAt);
|
|
|
+ const dd = String(date.getDate()).padStart(2, '0');
|
|
|
+ const mm = String(date.getMonth() + 1).padStart(2, '0');
|
|
|
+ const yyyy = date.getFullYear();
|
|
|
+ return `${dd}/${mm}/${yyyy}`;
|
|
|
+ });
|
|
|
const prices = data.map((item) => item.price);
|
|
|
|
|
|
if (chartInstance) {
|
|
|
@@ -72,17 +80,35 @@
|
|
|
});
|
|
|
}
|
|
|
|
|
|
- onMount(async () => {
|
|
|
- if (!code) return;
|
|
|
-
|
|
|
- const history = await fetchData();
|
|
|
+ async function updateChart(range) {
|
|
|
+ selectedRange = range;
|
|
|
+ const history = await fetchData(range);
|
|
|
if (history.length > 0) {
|
|
|
renderChart(history);
|
|
|
}
|
|
|
+ }
|
|
|
+
|
|
|
+ onMount(() => {
|
|
|
+ updateChart(selectedRange);
|
|
|
});
|
|
|
</script>
|
|
|
|
|
|
+
|
|
|
<div class="w-full mt-10 max-w-6xl mx-auto bg-white dark:bg-gray-900 p-6 rounded-xl shadow-md">
|
|
|
<h3 class="text-xl font-semibold text-gray-800 dark:text-gray-100 mb-4">Price History</h3>
|
|
|
<canvas bind:this={chartCanvas}></canvas>
|
|
|
+
|
|
|
+ <div class="flex justify-center gap-4 mt-6">
|
|
|
+ {#each ranges as range}
|
|
|
+ <button
|
|
|
+ class="px-4 py-2 rounded-md text-sm font-medium transition cursor-pointer
|
|
|
+ {selectedRange === range
|
|
|
+ ? 'bg-blue-500 text-white'
|
|
|
+ : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-100'}"
|
|
|
+ on:click={() => updateChart(range)}
|
|
|
+ >
|
|
|
+ {range.toUpperCase()}
|
|
|
+ </button>
|
|
|
+ {/each}
|
|
|
+ </div>
|
|
|
</div>
|